0

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?

4

2 回答 2

1

您应该@SupportedAnnotationTypes在处理器上使用注释,而不是覆盖该getSupportedAnnotationTypes()方法,例如:

@SupportedAnnotationTypes({"com.test.Interceptor"})
public class AnnotationProcessor extends AbstractProcessor {
    ...

Processor.getSupportedAnnotationTypes() 方法可以从这个注解的值构造它的结果,正如 AbstractProcessor.getSupportedAnnotationTypes() 所做的那样。

文档:

https://docs.oracle.com/javase/8/docs/api/javax/annotation/processing/SupportedAnnotationTypes.html

于 2016-06-26T16:40:04.030 回答
1

如果您的注解处理器正在扫描使用您的注解进行元注解的所有注解,您需要指定"*"您支持的注解类型,然后检查每个注解的声明(使用ProcessingEnvironment.getElements()以确定它是否具有感兴趣的元注解。

于 2016-06-26T16:49:23.023 回答