2

我们的项目中有两个注释,我想收集带注释的类并基于两个类列表创建合并输出。

这可能只有一个Processor实例吗?我如何知道Processor实例是否被每个带注释的类调用?

4

1 回答 1

3

框架仅调用该方法一次(每轮),您可以通过传递的参数Processor.process同时访问两个列表。RoundEnvironment因此,您可以在同一个process方法调用中处理这两个列表。

为此,请列出注释中的两个SupportedAnnotationTypes注释:

@SupportedAnnotationTypes({ 
    "hu.palacsint.annotation.MyAnnotation", 
    "hu.palacsint.annotation.MyOtherAnnotation" 
})
@SupportedSourceVersion(SourceVersion.RELEASE_6)
public class Processor extends AbstractProcessor { ... }

这是一个示例process方法:

@Override
public boolean process(final Set<? extends TypeElement> annotations, 
        final RoundEnvironment roundEnv) {
    System.out.println("   > ---- process method starts " + hashCode());
    System.out.println("   > annotations: " + annotations);

    for (final TypeElement annotation: annotations) {
        System.out.println("   >  annotation: " + annotation.toString());
        final Set<? extends Element> annotateds = 
            roundEnv.getElementsAnnotatedWith(annotation);
        for (final Element element: annotateds) {
            System.out.println("      > class: " + element);
        }
    }
    System.out.println("   > processingOver: " + roundEnv.processingOver());
    System.out.println("   > ---- process method ends " + hashCode());
    return false;
}

及其输出:

   > ---- process method starts 21314930
   > annotations: [hu.palacsint.annotation.MyOtherAnnotation, hu.palacsint.annotation.MyAnnotation]
   >  annotation: hu.palacsint.annotation.MyOtherAnnotation
      > class: hu.palacsint.annotation.p2.OtherClassOne
   >  annotation: hu.palacsint.annotation.MyAnnotation
      > class: hu.palacsint.annotation.p2.ClassTwo
      > class: hu.palacsint.annotation.p3.ClassThree
      > class: hu.palacsint.annotation.p1.ClassOne
   > processingOver: false
   > ---- process method ends 21314930
   > ---- process method starts 21314930
   > roots: []
   > annotations: []
   > processingOver: true
   > ---- process method ends 21314930

它打印所有使用MyAnnotationMyOtherAnnotation注释注释的类。

于 2012-07-29T21:20:34.880 回答