Processing different annotations with the same Processor instance

☆樱花仙子☆ 提交于 2019-12-13 17:03:48

问题


We have two annotations in our project and I'd like to collect the annotated classes and create a merged output based on both lists of classes.

Is this possible with only one Processor instance? How do I know if the Processor instance was called with every annotated class?


回答1:


The framework calls the Processor.process method only once (per round) and you can access both lists at the same time through the passed RoundEnvironment parameter. So you can process both lists in the same process method call.

To do this list both annotations in the SupportedAnnotationTypes annotation:

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

Here is a sample process method:

@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;
}

And its output:

   > ---- 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

It prints all classes which are annotated with the MyAnnotation or the MyOtherAnnotation annotation.



来源:https://stackoverflow.com/questions/11713059/processing-different-annotations-with-the-same-processor-instance

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!