How to current get executing method name & caller of the method in Java

Recently I was investigating issue in our internal software , where I needed to get the current executing method name ( similar to c++ __FUNCTION___ )  and caller name.

It is possible get this information using getting access to stack trace in java. see the example below.

public class DebugInfo {
  /**
   *
   * This function returns the method name of the calling functions parent
   * function
   *
   * @return
   */
  public static String getCallingMethodName() {

    StackTraceElement stack[] = Thread.currentThread().getStackTrace();

    StackTraceElement element = stack[3];

    return element.toString();
  }
  /**
   *
   * This function returns the method name of the calling function
   *
   * @return
   */
  public static String myMethodName() {

    StackTraceElement stack[] = Thread.currentThread().getStackTrace();

    StackTraceElement element = stack[2];

    return element.toString();
  }
}

Java2html
Usage:
public class Foo
{
public void bar()
{
   // print the current method name
   System.out.println( DebugInfo.myMethodName());
   // print the current calling method name
   System.out.println( DebugInfo.getCallingMethodName());
}
public static void main(String [] args )
{
    Foo f = new Foo();
            f.bar();
}
}

 

Advertisements