gpt4 book ai didi

java - Annotation 处理 unknown Annotation

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:36:43 29 4
gpt4 key购买 nike

目前我正在编写一个注释处理器,它将生成新的源代码。该处理器与应用程序本身隔离,因为它是构建项目的一个步骤,我将整个构建系统与应用程序分开。

这就是问题开始的地方,因为我想处理在应用程序中创建的注释。我们将其命名为 CustomAnnotation。使用完全限定名称 com.company.api.annotation.CustomAnnotation

在处理器中,我可以通过完全限定名称搜索注释,这真是太好了。现在我似乎能够获得注释的方法、字段等,因为我可以使用 TypeElement 而不是 Class 调用函数 getElementsAnnotatedWith

现在我们的 CustomAnnotation 中有字段和变量,通常我会像这样获得 Annotation 本身:Class annotation = Element.getAnnotation(Class) 但我不能使用它,因为 CustomAnnotation 不是作为类对象可用。(当然,处理器不知道它)我尝试使用 TypeMirror 和其他可用的东西,但似乎没有任何效果。

有没有人知道让注释读取它的值的方法?

编辑:让我们看看这个实现:

@SupportedAnnotationTypes( "com.company.api.annotation.CustomAnnotation" )
@SupportedSourceVersion( SourceVersion.RELEASE_8 )
public class CustomProcessor extends AbstractProcessor
{

public CustomProcessor()
{
super();
}

@Override
public boolean process( Set<? extends TypeElement> annotations, RoundEnvironment roundEnv )
{
TypeElement test = annotations.iterator().next();

for ( Element elem : roundEnv.getElementsAnnotatedWith( test ) )
{
//Here is where I would get the Annotation element itself to
//read the content of it if I can use the Annotation as Class Object.
SupportedAnnotationTypes generated = elem.getAnnotation( SupportedAnnotationTypes.class );
}
}

但是我不必使用 CustomAnnotation.class 因为它不存在于这个环境中。如果不拥有 Class 对象,我该如何做到这一点?

最佳答案

您可以将注解查询为 AnnotationMirror,它不需要注解类型是加载的运行时 Class:

@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
for(TypeElement test: annotations) {
for( Element elem : roundEnv.getElementsAnnotatedWith( test ) ) {
System.out.println(elem);
for(AnnotationMirror am: elem.getAnnotationMirrors()) {
if(am.getAnnotationType().asElement()==test)
am.getElementValues().forEach((ee,av) ->
System.out.println("\t"+ee.getSimpleName()+" = "+av.getValue())
);
}
}
}
return true;
}

关于java - Annotation 处理 unknown Annotation,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41041006/

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