目前我正在编写一个注释处理器,它将生成新的源代码。此处理器与应用程序本身是隔离的,因为它是构建项目的一个步骤,我将整个构建系统与应用程序分离开来。
这就是问题的起点,因为我想处理在应用程序中创建的注释。我们把它命名为CustomAnnotation.具有完全限定名com.company.api.annotation.CustomAnnotation.
在处理器中,我可以通过完全限定的名称搜索注释,真正好的是什么。现在,我似乎能够得到注释的方法、字段等,因为我可以用TypeElement而不是类调用函数。
现在我们的CustomAnnotation中有字段和变量,通常我会得到这样的注释: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对象的情况下,我如何做到这一点?
发布于 2016-12-08 06:13:45
您可以将注释查询为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;
}
https://stackoverflow.com/questions/41041006
复制相似问题