Annotation 处理 unknown Annotation

Annotation processing unknown Annotation

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

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

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

现在我们的 CustomAnnotation 中有字段和变量,通常我会像这样获得 Annotation 本身:Class annotation = Element.getAnnotation(Class) 但是我不能使用它,因为 CustomAnnotation 不能用作 Class 对象。 (当然,处理器不知道)我尝试使用 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;
}