Let’s say I have a situation like this:
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);
}
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?
You need to obtain the
Methodobject that represents the method that calledstringForThisVisibility. Unfortunately, Java doesn’t offer this functionality out of the box.However, we can still obtain the
Methodvia the information returned byThread.currentThread().getStackTrace(). That method returns an array ofStackTraceElementobjects. EachStackTraceElementobject tells us three things:getClassName())getMethodName())getLineNumber())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
StackTraceElementin the array).Once you have the desired
StackTraceElement, you can obtain its correspondingMethodobject using the technique in my answer to the question entitled “Get caller’s method (java.lang.reflect.Method)”. That technique will still word, even if the class has more than one method with that method name. There are simpler techniques if you’re not worried about that scenario.Once you have the
Methodobject, it’s just a matter of callingmethod.getAnnotation(VisibilityLevel.class).