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

JavaObject Oriented ProgrammingProgramming

Stack Walking API can provide a flexible mechanism to traverse and extract information from call stacks that allow us to filter and access frames in a lazy manner. StackWalker class is an entry point to Stack Walking API. The stack trace is a representation of a call stack at a certain point of time in which each element represents a method invocation. It contains all invocations from the start of a thread until the point it’s generated.

In the below example, we can print/display all stack frames of the current thread by using StackWalker API.

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.getDeclaredMethod("test1", (Class[])null);
      test1Method.invoke(null, (Object[]) null);
   }
}

// Helper1 class
class Helper1 {
   protected static void test1() {
      Helper2.test2();
   }
}

// Helper2 class
class Helper2 {
   protected static void test2() {
      List<StackFrame> stack = StackWalker.getInstance().walk((s) -> s.collect(Collectors.toList()));
      for(StackFrame frame : stack) {
         System.out.println(frame.getClassName() + " " + frame.getLineNumber() + " " +    frame.getMethodName());
      }
   }
}

Output

Helper2 23 test2
Helper1 16 test1
StackWalkerTest 9 main
raja
Published on 19-Mar-2020 07:36:28
Advertisements