StackWalker API in Java 9?

JavaObject Oriented ProgrammingProgramming

StackWalker API allows easy filtering and lazy access to execute tasks within any method. It is an efficient API for obtaining stack trace information in Java 9.

There are three new important classes in StackWalker API: StackWalker, StackWalker.StackFrame and StackWalker.Option.

StackWalker  It is the main class in StackWalker API. We traverse stack frames by using StackWalker.forEach() method and get caller class in an efficient way by calling StackWalker.getCallerClass() method. We walk through stack traces and applying a function on a stream of stack frames by using StackWalker.walk() method.

StackWalker.StackFrame  It is a static nested class of StackWalker and represents method invocation return by StackWalker. It has methods to access a given stack frame information like getDeclaringClass(), getLineNumber() and etc.

StackWalker.Option − It is a static nested class of StackWalker and provides options for the stack walker to configure the stack frame information when we create an instance via SackWalker.getInstance().


import java.util.List;
public class StackWalkingTest {
   public static void main(String args[]) {
      final List<StackWalker.StackFrame> stack = StackWalker.getInstance()
      .walk(s -> s.collect(Collectors.toList()));
      for(StackWalker.StackFrame sf : stack) {
         System.out.println(sf.getClassName() + "::" + sf.getMethodName() + ":" + sf.getLineNumber());


Published on 17-Feb-2020 16:07:06