Is there a way to get the name of the currently executing method in Java?
January 2009:
A full code would be (to use with @Bombe's caveat in mind):
/**
* Get the method name for a depth in call stack.
* Utility function
* @param depth depth in the call stack (0 means current method, 1 means call method, ...)
* @return method name
*/
public static String getMethodName(final int depth)
{
final StackTraceElement[] ste = Thread.currentThread().getStackTrace();
//System. out.println(ste[ste.length-depth].getClassName()+"#"+ste[ste.length-depth].getMethodName());
// return ste[ste.length - depth].getMethodName(); //Wrong, fails for depth = 0
return ste[ste.length - 1 - depth].getMethodName(); //Thank you Tom Tresansky
}
More in this question.
Update December 2011:
bluish comments:
I use JRE 6 and gives me incorrect method name.
It works if I writeste[2 + depth].getMethodName().
0isgetStackTrace(),1isgetMethodName(int depth)and2is invoking method.
virgo47's answer (upvoted) actually computes the right index to apply in order to get back the method name.