问题描述
我们已经在我们的项目中两个注解,我想基于类的两份名单,收集类中的注解,并创建一个合并输出。
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?
推荐答案
框架调用 Processor.process
方法只一次(每个轮),并可以访问两个列表在通过传递 RoundEnvironment
参数同一时间。所以,你可以在同一个工艺处理两份名单
方法调用。
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.
要做到这个列表中的 SupportedAnnotationTypes
注释都标注:
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 { ... }
下面是一个样本过程
方法:
@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
它打印这些注释的所有类 MyAnnotation
或 MyOtherAnnotation
注释。
这篇关于处理不同的注释具有相同的处理器实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!