java-name-of-executing-method
How to Get a Name of a Method Being Executed?
1. Overview
This quick article presents a couple of simple ways of getting hold of the method name in the current execution stack.
2. Using getEnclosingMethod
public void givenObject_whenGetEnclosingMethod_thenFindMethod() {
String methodName = new Object() {}
.getClass()
.getEnclosingMethod()
.getName();
assertEquals("givenObject_whenGetEnclosingMethod_thenFindMethod",
methodName);
}
3. Using Throwable Stack Trace
public void givenThrowable_whenGetStacktrace_thenFindMethod() {
StackTraceElement[] stackTrace = new Throwable().getStackTrace();
assertEquals(
"givenThrowable_whenGetStacktrace_thenFindMethod",
stackTrace[0].getMethodName());
}
4. Using Thread Stack Trace
Also, the stack trace of a current thread (since JDK 1.5) usually includes the name of the method that is being executed:
public void givenCurrentThread_whenGetStackTrace_thenFindMethod() {
StackTraceElement[] stackTrace = Thread.currentThread()
.getStackTrace();
assertEquals(
"givenCurrentThread_whenGetStackTrace_thenFindMethod",
stackTrace[1].getMethodName());
}
However, we need to remember that this solution has one significant drawback. Some virtual machines may skip one or more stack frames. Although this is not common, we should be aware that this can happen.
5. Conclusion
In this tutorial, we have presented some examples how to get the name of the currently executed method. Examples are based on stack traces and the getEnclosingMethod().
As always, you can check out the examples provided in this article over on GitHub.