Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Processing different annotations with the same Processor instance

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?

like image 621
palacsint Avatar asked Jun 29 '26 03:06

palacsint


1 Answers

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.

like image 86
palacsint Avatar answered Jun 30 '26 17:06

palacsint



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!