Home > Java > javaTutorial > How to display all stack frames of current thread in Java 9?

How to display all stack frames of current thread in Java 9?

WBOY
Release: 2023-09-05 20:09:06
forward
856 people have browsed it

在Java 9中如何显示当前线程的所有堆栈帧?

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.

Example
import 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>);
      }
   }
}
Copy after login

Output

<strong>Helper2 23 test2
Helper1 16 test1
StackWalkerTest 9 main</strong>
Copy after login

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!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template