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

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s