views:

1931

answers:

2

Is there a way to get the name of the currently executing method in Java?

+8  A: 

Thread.currentThread().getStackTrace() will usually contain the method you’re calling it from but there are pitfalls.

Some virtual machines may, under some circumstances, omit one or more stack frames from the stack trace. In the extreme case, a virtual machine that has no stack trace information concerning this thread is permitted to return a zero-length array from this method.

Bombe
Is this same pitfall true for stack traces in exceptions?
drhorrible
+9  A: 

a full code would be (to use with with Bombe's caveat in mind):

  /**
   * Get the method name for a depth in call stack. <br />
   * Utility function
   * @param depth depth in the call stack (0 means current method, 1 means call method, ...)
   * @return method name
   */
  public static String getMethodName(final int depth)
  {
    final StackTraceElement[] ste = Thread.currentThread().getStackTrace();

    //System. out.println(ste[ste.length-depth].getClassName()+"#"+ste[ste.length-depth].getMethodName());
    return ste[ste.length - depth].getMethodName();
  }

More in this question.

VonC
Fails for depth = 0. Should be: return ste[ste.length - 1 - depth].getMethodName();
Tom Tresansky