I have an custom annotation called @Pojo which I use for automatic wiki documentation generation:
package com.example.annotations;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.SOURCE)
@Target(ElementType.METHOD)
public @interface Pojo {
Class> value();
}
I use it like this:
@Pojo(com.example.restserver.model.appointment.Appointment.class)
to annotation a resource method so that the annotation processor can automatically generate a wiki page describing the resource and type that it expects.
I need to read the value of the value field in an annotation processor, but I am getting a runtime error.
In the source code for my processor I have the following lines:
final Pojo pojo = element.getAnnotation(Pojo.class);
// ...
final Class> pojoJavaClass = pojo.value();
but the actual class in not available to the processor. I think I need a javax.lang.model.type.TypeMirror instead as a surrogate for the real class. I'm not sure how to get one.
The error I am getting is:
javax.lang.model.type.MirroredTypeException: Attempt to access Class object for TypeMirror com.example.restserver.model.appointment.Appointment
The Appointment is a class mentioned in one of my @Pojo annotation.
Unfortunately, document and/or tutorials on Java annotation processing seems scarce. Tried googling.
解决方案
There the trick is to actually use getAnnotation() and catch the MirroredTypeException. Surprisingly the exception then provides the TypeMirror of the required class.
I don't know if this is a good solution, but it is one. In my personal opinion I would try to get the type behind the MirroredType, but I don't know if this is possible.