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
}
}
System.out.println(new Exception().getStackTrace()[0].getMethodName());
Also See
Method lastMethodCalled = this.getClass().getEnclosingMethod();