Close

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

Java Stack Walking Java 

Following example shows how to get Caller information of the current method by using Java 9 StackWalker.

package com.logicbig.example;

public class StackWalkerUtil {

public static String getCaller() {
StackWalker stackWalker = StackWalker.getInstance(StackWalker.Option.RETAIN_CLASS_REFERENCE);
StackWalker.StackFrame frame = stackWalker.walk(stream1 -> stream1.skip(2)
.findFirst()
.orElse(null));
if (frame == null) {
return "caller: null";
}
return String.format("caller: %s#%s, %s",
frame.getClassName(),
frame.getMethodName(),
frame.getLineNumber()
);
}

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

public static void testMethod() {
//gets caller of the current method
String caller = getCaller();
System.out.println(caller);
}
}

Output

caller: com.logicbig.example.StackWalkerUtil#main, 31
See Also Java 9 StackWalker tutorial.




See Also