我正在玩 Java (javax) 注释处理。
假设我有一个方法注释:
@Target(ElementType.METHOD)
public @interface MethodAnnotation { }
现在我想处理所有被带注释方法的类型覆盖的方法:
interface MyInterface() {
@MethodAnnotation
void f()
}
class MyClass implements MyInterface {
override void f() { } // <- I want to process this method
}
@Inherited
元注释似乎不适合这里:
Note that this meta-annotation type has no effect if the annotated type is used to annotate anything other than a class.
另外,是否可以处理未在子类中覆盖的继承类方法?像这样:
class MyClass {
@MethodAnnotation
void f() { }
}
class MySubClass extends MyClass { } // <- I want to process its f()
// or at least to find out that it doesn't
// override the method
如何访问 AbstractProcessor
中某个方法的覆盖方法?
我想,要实现这一点,我需要找到封闭类的子类,但我也没有找到方法。
UPD:我想可以使用 RoundEnvironment.getRootElements()
,但仍然没有找到合适的方法。
最佳答案
简短的回答是,开箱即用的注释处理不会让您轻松做到这一点,但它可以做到。
您实际上将不得不处理每个方法并自己进行过滤,而不是使用正常的调度机制进行处理。
第 1 步:
定义您的处理器,使其 supports all annotations通过使用 "*"
作为其支持的注释类型。这意味着您的处理器将在每一轮中被调用。
第 2 步:
使用 getRootElements
每轮获取整个元素集。
第三步:
创建一个 ElementScanner8
遍历您找到的任何元素以查找 ExecutableElement
。如果您愿意相信重写的方法是用 @Override
注释的,那么您可以对它们进行快速过滤。否则,只需查看所有这些。
第四步:
现在您需要查看该方法是否覆盖了带有您要查找的注解的方法。没有简单的方法来获取给定方法已覆盖的方法,因此您需要获取 enclosing element的方法,看它的superclass和 implemented interfaces (递归),得到他们的enclosed elements , filter out the methods , 和 test to see if it has been overridden通过有问题的方法。如果有,可以查看annotations看看它是否有你关心的人。
第五步:
此时,您应该拥有您正在寻找的重写方法、重写方法和注解镜像,因此您应该能够实现您想要的任何逻辑。
关于java - 如何在注释处理中引用方法的实现?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38292131/