APT如何处理嵌套注释类的注释

时间:2012-10-11 19:35:49

标签: java annotations nested apt 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 }     
    }
}

如何在处理过程中访问嵌套的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()  );
        }
    }
}

2 个答案:

答案 0 :(得分:0)

我想这取决于这些注释是如何相互关联的。

你可以简单地在@SupportedAnnotationTypes中声明所有注释,并在process-method中有几个块,如:

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);
    }
}

否则,您可以使用element.getEnclosedElements()element.getEnclosingElement()来实现您的目标。

答案 1 :(得分:-1)

您需要ClassMethod中的一些方法来执行此操作,特别是要获取Foo中声明的类,这些类的注释,在这些类中声明的方法类,以及这些方法的注释。这是一个简单的例子:

public static void main(String... args) {
    for (Class<?> declaredClass : Foo.class.getDeclaredClasses()) {
        MyAnnotation myAnnotation = declaredClass.getAnnotation(MyAnnotation.class);
        // Process value of class annotation here
        for (Method method : declaredClass.getDeclaredMethods()) {
            MyMethodAnnotation myMethodAnnotation = method.getAnnotation(MyMethodAnnotation.class);
            // Process value of method annotation here
        }
    }
}

阅读有关Java中的反射的文档可能很有见地:http://docs.oracle.com/javase/tutorial/reflect/index.html