gpt4 book ai didi

java - APT 如何处理嵌套注解类的注解

转载 作者:搜寻专家 更新时间:2023-10-31 08:04:35 24 4
gpt4 key购买 nike

我正在尝试使用 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() );
}
}
}

最佳答案

我想这取决于这些注解如何相互关联。

您可以简单地在@SupportedAnnotationTypes 中声明所有注释,并在过程方法中有几个 block ,例如:

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.getEnclosedElement() 来实现您想要的。

关于java - APT 如何处理嵌套注解类的注解,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12847187/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com