Real'sHowTo AddThis Feed Button
Custom Search

Get the current method nameTag(s): Language


JDK1.4

public class MyTest {
    public static void main(String args[]) {
      new MyTest().doit();
    }
    public void doit() {
      System.out.println
         (new Exception().getStackTrace()[0].getMethodName());
    }
}
The output
doit

JDK1.5

While the above snippet is not bad, it is expensive since we need to create an Exception.

With JDK1.5, a new technique is available.

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

 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");
   }
 }
}

main
doit
doitagain
main
To get the calling method
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.


blog comments powered by Disqus


If you find this article useful, consider making a small donation
to show your support for this Web site and its content.

Written and compiled by Réal Gagnon ©1998-2013
[ home ]