Reputation: 472
I'm writing my own annotation processor and I'm trying to get parameter of my annotation like in the code below in process method:
roundEnv.getElementsAnnotatedWith(annotation).forEach {
val annotation = it.getAnnotation(annotation)
annotation.interfaces
}
What I get is An exception occurred: javax.lang.model.type.MirroredTypesException: Attempt to access Class objects for TypeMirrors []
during build. Anyone know how to get annotation data?
Upvotes: 4
Views: 3316
Reputation: 21497
This blog post seems to be the canonical source for how to do this. It references a Sun forum discussion and is referenced in a number of annotation processors.
For the following annotation:
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Action {
Class<?> value();
}
The field of type Class<?>
can be accessed through this code:
for (ExecutableElement ee : ElementFilter.methodsIn(te.getEnclosedElements())) {
Action action = ee.getAnnotation(Action.class);
if (action == null) {
// Look for the overridden method
ExecutableElement oe = getExecutableElement(te, ee.getSimpleName());
if (oe != null) {
action = oe.getAnnotation(Action.class);
}
}
TypeMirror value = null;
if (action != null) {
try {
action.value();
} catch (MirroredTypeException mte) {
value = mte.getTypeMirror();
}
}
System.out.printf(“ % s Action value = %s\n”,ee.getSimpleName(), value);
}
Upvotes: 0
Reputation: 25603
The documentation on the getAnnotation
method explains why Class<?>
objects are problematic for an annotation processor:
The annotation returned by this method could contain an element whose value is of type Class. This value cannot be returned directly: information necessary to locate and load a class (such as the class loader to use) is not available, and the class might not be loadable at all. Attempting to read a Class object by invoking the relevant method on the returned annotation will result in a MirroredTypeException, from which the corresponding TypeMirror may be extracted. Similarly, attempting to read a Class[]-valued element will result in a MirroredTypesException.
To access annotation elements like classes you need to instead use Element.getAnnotationMirrors()
and manually find the annotation of interest. These annotation mirrors will contain elements representing the actual values but without requiring the presence of the classes in question.
Upvotes: 10