I was wondering if there is a way to know the method name being executed at run time?
For instance, inside a private void doSomething (String s) method, I'd like to know that I am executing the doSomething (String s) method.
I was wondering if there is a way to know the method name being executed at run time?
For instance, inside a private void doSomething (String s) method, I'd like to know that I am executing the doSomething (String s) method.
Since JDK1.5, you don't need an Exception to get the StackTrace,
you can get it with Thread.currentThread().getStackTrace()]:
public class Test2 {
public static void main(String args[]) {
new Test2().doit();
}
public void doit() {
System.out.println(
Thread.currentThread().getStackTrace()[1].getMethodName()); // output : doit
}
}
StackTraceElement [] ste = Thread.currentThread().getStackTrace(); for (StackTraceElement s : ste) { System.out.println(s); } , are you using a Sun JRE ?Thread.currentThread().getStackTrace()[2].getMethodName()System.out.println(new Exception().getStackTrace()[0].getMethodName());
Also See
Exception each time, which saves resources (checkout RealHowTo's answer above).