Close

Java Stack Walking - How to find name of the current method?

Java Stack Walking Java 

Following example shows how to find the current method name by using Java 9 StackWalker.

package com.logicbig.example;

public class StackWalkerCurrentMethodName {

public static String getCurrentMethodName() {
StackWalker stackWalker = StackWalker.getInstance(StackWalker.Option.RETAIN_CLASS_REFERENCE);
StackWalker.StackFrame frame = stackWalker.walk(stream1 -> stream1.skip(1)
.findFirst()
.orElse(null));
return frame == null ? "caller: null" : frame.getMethodName();
}

public static void main(String[] args) {
testMethod();
}

public static void testMethod() {
String methodName = getCurrentMethodName();
System.out.println(methodName);
}
}

[JDK 10]

Output

testMethod
See Also Java 9 StackWalker tutorial.




See Also