Share this page 

Get the current or calling method nameTag(s): Language


JDK1.4+
Get the current method
public class MyTest {
    public static void main(String args[]) {
      new MyTest().doit();
    }
    public void doit() {
      System.out.println
         (new Exception().getStackTrace()[0].getMethodName()); // output :doit
    }
}
JDK1.5+
While the above snippet is not bad, it is expensive since we need to create an Exception each time we needa trace.

With JDK1.5, a better technique is available to get the current method.

public class Test {
 public static void main(String args[]) {
    trace(Thread.currentThread().getStackTrace()); // output :main
    new Test().doit();
    trace(Thread.currentThread().getStackTrace()); // output :main
 }
 public void doit() {
    trace(Thread.currentThread().getStackTrace()); // output :doit
    doitagain();
  }
 public void doitagain() {
    trace(Thread.currentThread().getStackTrace()); // output : doitagain
  }

 public static void trace(StackTraceElement e[]) {
   boolean doNext = false;
   for (StackTraceElement s : e) {
       if (doNext) {
          System.out.println(s.getMethodName());
          return;
       }
       doNext = s.getMethodName().equals("getStackTrace");
   }
 }
}

Now we know how to get the current method. If we need the calling instead instead :

public class Test {
 public static void main(String args[]) {
    new Test().doit();
 }
 public void doit() {
    System.out.println(
       Thread.currentThread().getStackTrace()[2].getMethodName()); // output : main
 }
}

See also this Howto

  • Trace the execution.