问题描述
假设我有这样的情况:
public String method(String s) {
return stringForThisVisibility(s, EnumVisibility.PUBLIC);
}
我想用这样的注释替换它:
and I want to replace it with an annotation like this:
@VisibilityLevel(value = EnumVisibility.PUBLIC)
public String method(String s) {
return stringForThisVisibility(s);
}
这似乎是一个更好更清晰的解决方案,但我需要stringForThisVisibility用某种反射知道@VisibilityLevel值的方法。那可能吗?我可以在调用stringForThisVisibility的方法上看到注释吗?
This seems to be a better and more clear solution, but i need for stringForThisVisibility method to know value of @VisibilityLevel with some kind of reflection. Is that possible? Can I see the annotations on the method calling stringForThisVisibility?
推荐答案
您需要获取对象表示调用 stringForThisVisibility
的方法。遗憾的是,Java并不提供开箱即用的功能。
You need to obtain the Method
object that represents the method that called stringForThisVisibility
. Unfortunately, Java doesn't offer this functionality out of the box.
但是,我们仍然可以获得方法
通过。该方法返回一个对象。每个 StackTraceElement
对象告诉我们三件事:
However, we can still obtain the Method
via the information returned by Thread.currentThread().getStackTrace()
. That method returns an array of StackTraceElement
objects. Each StackTraceElement
object tells us three things:
- name of class()
- 方法的名称()
- 行号()
- The name of the class (
getClassName()
) - The name of the method (
getMethodName()
) - The line number (
getLineNumber()
)
可能需要一些实验,但您应该找到该数组中的哪个索引代表您感兴趣的方法(它可能是第一个,第二个或第三个数组中的StackTraceElement
。
It may take some experimentation, but you should find which index in that array represents the method you're interested in (it will probably be the first, second or third StackTraceElement
in the array).
一旦你有了所需的 StackT raceElement
,您可以使用题为。
Once you have the Method
object, it's just a matter of calling method.getAnnotation(VisibilityLevel.class)
.
这篇关于请参阅调用方法的java注释的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!