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