我想从调用另一个方法的方法的注释中获取一个值,该值需要与被调用方法中使用的注释一起使用。
例子
@MyAnnotation(id="method-invoker")
public void invoker(){
executor();
}
@ChildMethod
public void executor(){
}
在上面的示例中,我想在处理 @ChildMethod
注释时在 @MyAnnotation
的 id
字段中设置值。
我该怎么做?
最佳答案
首先你必须获取堆栈跟踪,然后从中提取调用者的姓名,然后获取方法
并获取其注释:
String id = getClass().getMethod(new Throwable().getStackTrace()[1].getMethodName()).getAnnotation(MyAnnotation.class).id();
(显然,在一行中按顺序执行如此多的调用是一种糟糕的风格,但例如这样是可以的)。
但这种方法有局限性。它不支持方法重载。例如,如果您有 2 个名为 invoker()
的方法,它们在一个类中具有不同的签名,您无法使用纯反射 API 区分它们。
幸运的是我实现了名为 CallStack 的库可以做到这一点:https://github.com/alexradzin/callstack
使用 CallStack
你可以说:
CallStack.getCallStack().getFunction().getAnnotation(MyAnnotation.class).id()
关于java - 获取调用方法的注解值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26865853/