问题
Given this annotation:
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.ANNOTATION_TYPE)
public @interface Interceptor {
Class<? extends Behaviour> value();
}
The users of my library can extend its API creating custom annotations annotated with @Interceptor
, as follows:
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Interceptor(BypassInterceptor.class)
public @interface Bypass {
}
AbstractProcessor provides a method called getSupportedAnnotationTypes which returns the names of the annotation types supported by the processor. But if I specify the name of @Interceptor
, as follows:
@Override public Set<String> getSupportedAnnotationTypes() {
Set<String> annotations = new LinkedHashSet();
annotations.add(Interceptor.class.getCanonicalName());
return annotations;
}
The processor#process method will not be notified when a class is annotated with @Bypass
annotation.
So, when using an AbstractProcessor
, how to claim for annotations which target is another annotation?
回答1:
If your annotation processor is scanning for all annotations that are meta-annotated with your annotation, you'll need to specify "*"
for your supported annotation types, and then inspect each annotation's declaration (using ProcessingEnvironment.getElements()
to determine whether it has the meta-annotation of interest.
回答2:
You should use the @SupportedAnnotationTypes
annotation on your processor, and not override the getSupportedAnnotationTypes()
method, for example:
@SupportedAnnotationTypes({"com.test.Interceptor"})
public class AnnotationProcessor extends AbstractProcessor {
...
The Processor.getSupportedAnnotationTypes() method can construct its result from the value of this annotation, as done by AbstractProcessor.getSupportedAnnotationTypes().
Javadoc:
https://docs.oracle.com/javase/8/docs/api/javax/annotation/processing/SupportedAnnotationTypes.html
来源:https://stackoverflow.com/questions/38036862/abstractprocessor-how-to-claim-for-annotations-which-target-is-another-annotati