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().

Example

import java.util.List;
import java.util.stream.Collectors;
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());
      }
   }
}

Output

StackWalkingTest::main:6
raja
Published on 17-Feb-2020 11:37:06
Advertisements