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?
Advertisement
Answer
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.