假设我有这个类(class):
public class MyClass extends Ancestor{
@MyAnnotation
void doSomething(){
}
@MyAnnotation
void doAnotherthing(String[] args){
}
}
public class Ancestor{
@MyAnnotation
void doFirst(){
}
}
在我的注释处理器中,我有一个 MyClass
的 TypeElement
实例。
如何在 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
是必需的,因为您还想查找父类(super class)上的方法。没有它也是可以的,但这确实比必要的工作多得多。
参见Elements#getAllMembers
, Element#getAnnotation
还有TypeElement#getEnclosedElements
.
I know it's possible with RoundEnvironment but i don't want to use it
来自 RoundEnvironment#getElementsAnnotatedWith
的文档:
Only package elements and type elements included in this round of annotation processing, or declarations of members, constructors, parameters, or type parameters declared within those, are returned.
实际上,RoundEnvironment
可能会也可能不会用于查找一般带注释的元素,具体取决于您在做什么。 RoundEnvironment
上的方法特别对于查找使用您正在处理的注释进行注释的元素非常有用。
当然,如果您想将搜索范围缩小到更小的范围(在您的例子中是MyClass
),那也是非常糟糕的。 RoundEnvironment
找到一切。例如,如果我们想查找某个特定类 Bar
从其父类(super class) Foo
重写的方法,RoundEnvironment
对此非常尴尬。我们必须找到覆盖任何内容的所有方法,然后使用getEnendingElement()
来查找属于Bar
的方法。
例如,如果您正在为 MyAnnotation
编写注释处理器,那么使用 RoundEnvironment
会更有意义,因为注释不一定在单轮中处理。自己搜索注释而不是通过 RoundEnvironment
可能会导致您找到已在上一轮中处理过的注释。
关于java - 如何在TypeElement中查找带注释的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36801958/