sho*_*mes 6 java apt annotations nested annotation-processing
我正在尝试使用java编写注释处理器.此批注处理器需要在带注释的类中标识带注释的嵌套类,如下所示.我将首先处理带注释的类,然后处理它们的内部注释.这是在编译时执行的,我将不知道正在处理的类.在Foo中可以有多个嵌套类.如何处理所有这些嵌套类的注释.
@MyAnnotation(value="Something important")
public class Foo
{
private Integer A;
@MyMethodAnnotation(value="Something Else")
public Integer getA() { return this.A; }
@MyAnnotation(value="Something really important")
private class Bar
{
private Integer B;
@MyMethodAnnotation(value="Something Else that is very Important")
public Integer getB() { return this.B }
}
}
Run Code Online (Sandbox Code Playgroud)
如何在处理过程中访问嵌套的Bar类,它是注释"MyAnnotation"及其"MyMethodAnnotation"?以下代码仅打印有关类Foo的信息.如何处理有关Bar的信息?
for (Element element : env.getElementsAnnotatedWith(MyAnnotation.class)) {
if ( element.getKind().equals(ElementKind.CLASS) )
{
System.out.println(element.getKind().name() + " " + element.getSimpleName() );
processInnerClassElement(element);
}
else
{
System.out.println(element.getKind().name() + " " + element.getSimpleName() );
}
}
...
private void processInnerClassElement(Element element)
{
for (Element e : element.getEnclosedElements() )
{
if ( e.getKind().equals(ElementKind.CLASS) )
{
System.out.println(e.getKind().name() + " " + e.getSimpleName() );
processInnerClassElement(e);
}
else
{
System.out.println(e.getKind().name() + " " + e.getSimpleName() );
}
}
}
Run Code Online (Sandbox Code Playgroud)
我想这取决于这些注释如何相互关联。
您可以简单地在 @SupportedAnnotationTypes 中声明所有注释,并在流程方法中包含多个块,例如:
for (Element element : roundEnv.getElementsAnnotatedWith(MyAnnotation.class)) {
MyAnnotation myAnnotation = element.getAnnotation(MyAnnotation.class);
if (myAnnotation != null) {
doSomething(myAnnotation, element);
}
}
for (Element element : roundEnv.getElementsAnnotatedWith(MyMethodAnnotation.class)) {
MyMethodAnnotation myMethodAnnotation = element.getAnnotation(MyMethodAnnotation.class);
if (myMethodAnnotation != null) {
doSomething(myMethodAnnotation, element);
}
}
Run Code Online (Sandbox Code Playgroud)
否则你也许能够使用element.getEnclosedElements()并element.getEnclosingElement()实现你想要的东西。
| 归档时间: |
|
| 查看次数: |
2970 次 |
| 最近记录: |