Stack Walking API can provide a flexible mechanism to walk the call stack and extract information, allowing us to filter and access frames in a lazy manner. The StackWalker class is the entry point of the Stack Walking API. A stack trace represents a call stack at a point in time, where each element represents a method call . It contains all calls from thread startup to spawn.
In the following example, we can use StackWalker API to print/display all stack frames of the current thread.
Exampleimport java.lang.StackWalker.StackFrame; import java.lang.reflect.Method; import java.util.List; import java.util.stream.Collectors; public class StackWalkerTest { public static void main(String args[]) throws Exception { Method test1Method = Helper1.class.<strong>getDeclaredMethod</strong>("test1", (Class<!--?-->[])null); test1Method.invoke(null, (Object[]) null); } } <strong>// Helper1 class </strong>class Helper1 { protected static void test1() { Helper2.test2(); } } <strong>// Helper2 class</strong> class Helper2 { protected static void test2() { <strong>List<StackFrame></strong> stack = <strong>StackWalker.getInstance().walk</strong>((s) -> s.<strong>collect</strong>(Collectors.toList())); for(<strong>StackFrame </strong>frame : stack) { System.out.println(frame.<strong>getClassName()</strong> + " " + frame.<strong>getLineNumber()</strong> + " " + frame.<strong>getMethodName()</strong>); } } }
<strong>Helper2 23 test2 Helper1 16 test1 StackWalkerTest 9 main</strong>
The above is the detailed content of How to display all stack frames of current thread in Java 9?. For more information, please follow other related articles on the PHP Chinese website!