首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
社区首页 >问答首页 >注释处理未知注释

注释处理未知注释
EN

Stack Overflow用户
提问于 2016-12-08 05:45:06
回答 1查看 811关注 0票数 4

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

这就是问题的起点,因为我想处理在应用程序中创建的注释。我们把它命名为CustomAnnotation.具有完全限定名com.company.api.annotation.CustomAnnotation.

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

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

有人知道如何让注释读取它的值吗?

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

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
@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对象的情况下,我如何做到这一点?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-12-08 06:13:45

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

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
@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;
}
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/41041006

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档
查看详情【社区公告】 技术创作特训营有奖征文