See java annotations on call

Let's say I have this situation:

public String method(String s) {
    return stringForThisVisibility(s, EnumVisibility.PUBLIC);
}

and I want to replace it with annotation as follows:

@VisibilityLevel(value = EnumVisibility.PUBLIC)
public String method(String s) {
    return stringForThisVisibility(s);
}

This seems to be a better and clearer solution, but I need the stringForThisVisibility method to know the @VisibilityLevel value with some reflection. Is it possible? Can I view annotations of a method that calls stringForThisVisibility?

+5
source share
3 answers

You need to get an object Methodthat represents a method called stringForThisVisibility. Unfortunately, Java does not offer this functionality out of the box.

Method , Thread.currentThread().getStackTrace(). StackTraceElement. StackTraceElement :

, , (, , StackTraceElement ).

StackTraceElement, Method, , " (java.lang.reflect.Method)" . - , . , .

Method, method.getAnnotation(VisibilityLevel.class).

+5

:

 /**
   * Proper use of this class is
   *     String testName = (new Util.MethodNameHelper(){}).getName();
   *  or
   *     Method me = (new Util.MethodNameHelper(){}).getMethod();
   * the anonymous class allows easy access to the method name of the enclosing scope.
   */
  public static class MethodNameHelper {
    public String getName() {
      final Method myMethod = this.getClass().getEnclosingMethod();
      if (null == myMethod) {
        // This happens when we are non-anonymously instantiated
        return this.getClass().getSimpleName() + ".unknown()"; // return a less useful string
      }
      final String className = myMethod.getDeclaringClass().getSimpleName();
      return className + "." + myMethod.getName() + "()";
    }

    public Method getMethod() {
      return this.getClass().getEnclosingMethod();
    }
  }

:       me = ( Util.MethodNameHelper() {}). GetMethod();

getName() . 1500 . StackElement 30 (47000 ) .

+8

, . -

StackTraceElement[] stack = Thread.currentThread().getStackTrace();
Class callerClass = Class.forName(stack[stack.length-2].getClassName());
callerClass.isAnnotationPresent(...)

. ( ) . , .

+6

All Articles