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

Sae*_*umi 1 java annotation-processing

假设我有这样的课程:

public class MyClass extends Ancestor{

    @MyAnnotation
    void doSomething(){
    }

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

}

public class Ancestor{

    @MyAnnotation
    void doFirst(){
    }
}
Run Code Online (Sandbox Code Playgroud)

在我的注释处理器中,我有TypeElement一个MyClass.

如何@MyAnnotation在两者MyClass及其祖先中找到带注释的方法?

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

Rad*_*def 5

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;
}
Run Code Online (Sandbox Code Playgroud)

当然,您也可以过滤例如仅带有 的方法e.getKind() == ElementKind.METHOD

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

Elements#getAllMembersElement#getAnnotation且也TypeElement#getEnclosedElements

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

从文档中RoundEnvironment#getElementsAnnotatedWith

仅返回本轮注释处理中包含的包元素和类型元素,或者其中声明的成员、构造函数、参数或类型参数的声明。

因此,实际上,RoundEnvironment通常可能会或可能不会用于查找带注释的元素,具体取决于您在做什么。方法对于查找使用您正在处理的注释进行注释的元素特别RoundEnvironment有用。

当然,如果您想将搜索范围缩小到更小的范围(在您的情况下,MyClass. RoundEnvironment找到一切。比如说,如果我们想找到某个特定类Bar从其超类重写的方法FooRoundEnvironment那就非常尴尬了。我们必须找到所有覆盖任何内容的方法,然后使用getEnclosingElement()来查找属于 的方法Bar

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