繁体   English   中英

如何在TypeElement中找到带注释的方法?

[英]How to find annotated methods in TypeElement?

假设我有这个课程:

public class MyClass extends Ancestor{

    @MyAnnotation
    void doSomething(){
    }

    @MyAnnotation
    void doAnotherthing(String[] args){
    }

}

public class Ancestor{

    @MyAnnotation
    void doFirst(){
    }
}

在注释处理器中,我具有MyClassTypeElement实例。

如何在MyClass及其祖先中使用@MyAnnotation查找带注释的方法?

(我知道RoundEnvironment是可能的,但我不想使用它)

static Set<Element> getAnnotatedElements(
    Elements elements,
    TypeElement type,
    Class<? extends Annotation> annotation)
{
    Set<Element> found = new HashSet<Element>();
    for (Element e : elements.getAllMembers(type)) {
        if (e.getAnnotation(annotation) != null)
            found.add(e);
    }
    return found;
}

当然,您也可以使用e.getKind() == ElementKind.METHOD仅过滤例如方法。

Elements是必需的,因为您也想在超类上找到方法。 没有它也是可以做到的,但实际上要做的工作比必要的多。

请参见Elements#getAllMembersElement#getAnnotation以及TypeElement#getEnclosedElements

我知道RoundEnvironment有可能,但我不想使用它

RoundEnvironment#getElementsAnnotatedWith的文档中:

仅返回此批处理中包括的包元素和类型元素,或在其中声明的成员,构造函数,参数或类型参数的声明。

因此,实际上,根据您在做什么, RoundEnvironment可能会或可能无法找到带注释的元素。 RoundEnvironment上的方法对于查找使用您正在处理的注释进行注释的元素特别有用。

当然,如果您想将搜索范围缩小到较小的范围(例如MyClass ,那将是非常糟糕的。 RoundEnvironment可以找到所有内容 例如,如果我们想从其超类Foo查找某些特定类Bar覆盖的方法, RoundEnvironment对此非常尴尬。 我们必须找到覆盖所有内容的所有方法,然后使用getEnclosingElement()查找属于Bar

例如,如果您正在MyAnnotation编写注释处理器,那么使用RoundEnvironment会更有意义,因为注释不必在单个回合中进行处理。 自己搜索注释而不是通过RoundEnvironment可能会导致您找到上一轮已经处理过的注释。

如果编写注释处理器,则必须使用RoundEnvironment。 这就是注释处理器的工作方式。 请记住,javac可能会根据其内部需求多次运行您

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM