Wednesday, January 14, 2009

How to get the name of the currently executing method in Java ?

We can get the name of currently executing method using
Thread.currentThread.getStackTrace().
This will usually contain the method we are calling. But there are some pitfalls.
Some virtual machines may, under some circumstances, omit one or more stack frames from the stack trace. In the extreme case, a virtual machine that has no stack trace information concerning this thread is permitted to return a zero-length array from this method.

You can use the below code

final StackTraceElement[] ste = Thread.currentThread().getStackTrace();
ste[0].getMethodName(); // Will return the stack trace's first method name