Sunday, March 3, 2013

The calling method's name

The calling method's name can be simply obtained in one line:
String methodName = new Throwable().getStackTrace()[1]
        .getMethodName();
The Throwable class creates the stack trace snapshot using a native method (this functionality is implemented by JVM) and is surprisingly effective and efficient.
We are interested in the second (index [1]) stacktrace frame since the first one (index [0]) refers to the method currently being executed. The stacktrace frame also contains information like calling class's name and invoking line's number.
AFAIK this is how logging frameworks like log4j obtain the function name used by log formatters (logging patterns).

See more: http://docs.oracle.com/javase/7/docs/api/java/lang/Throwable.html