【发布时间】:2012-07-29 21:20:34
【问题描述】:
我们的项目中有两个注释,我想收集带注释的类并根据两个类列表创建合并输出。
只有一个Processor 实例可以做到这一点吗?我如何知道每个带注释的类是否调用了 Processor 实例?
【问题讨论】:
标签: java annotations annotation-processing
我们的项目中有两个注释,我想收集带注释的类并根据两个类列表创建合并输出。
只有一个Processor 实例可以做到这一点吗?我如何知道每个带注释的类是否调用了 Processor 实例?
【问题讨论】:
标签: java annotations annotation-processing
框架只调用一次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
它打印所有带有MyAnnotation 或MyOtherAnnotation 注释的类。
【讨论】: