java - Annotation 处理 unknown Annotation

标签 java annotations java-8 preprocessor

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

这就是问题开始的地方,因为我想处理在应用程序中创建的注释。我们将其命名为 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/

相关文章:

java - 如何调试 Spring 注解?

ios - 未保存 PDF 注释

java - 通过 Maven 或 Eclipse 使用和检查 Android 支持注释(无需 Android Studio)

java - Java 8 的构造函数引用的实际应用?

java - Oracle OJDBC 驱动程序抛出 NoClassDefFoundError : oracle/i18n/util/LocaleMapper

java - 安卓工作室模块

java - mysql 与 java 的连接....我很困惑

asp.net-mvc - 在 Controller 级别应用时如何禁用操作属性?

java - JDK 是否提供了一个虚拟消费者?

java - ArrayList::new 中出现不需要的内存不足错误 - 为什么?