How to filter stack frames using StackWalker API in Java 9?

StackWalker API provides a stream of information in stack traces during the execution of a program. This API requires a virtual machine to capture a snapshot of the entire stack and returns an array of elements for filtering purposes. We need to skip, drop, and limit the stack frames by using the walk() method. We can also filter a stack frame by class for getting the first matching frame, and all matching frames by using the filter() method.

In the below example, we can filter a stack frame by using StackWalker API.


import java.lang.StackWalker.StackFrame;
import java.util.*;

public class StackWalkerFilterTest {
   public static void main(String args[]) {
      final List<Class> filterClasses = new ArrayList<>();

      System.out.println("--- filter Frame by Class >> get first matching frame ---");
      Optional<StackFrame> frameByClass = findFrameByClass(filterClasses);

      System.out.println("--- filter Frame by Class >> get all matching frames ---");
      List<StackFrame> framesByClass = findAllFramesByClass(filterClasses);
   private static Optional<StackFrame> findFrameByClass(List<Class> filterClasses) {
      return StackWalker.getInstance(StackWalker.Option.RETAIN_CLASS_REFERENCE)
.walk(s -> s.filter(f -> filterClasses.contains(f.getDeclaringClass())).findFirst());
   private static List<StackFrame> findAllFramesByClass(List<Class> filterClasses) {
      return StackWalker.getInstance(StackWalker.Option.RETAIN_CLASS_REFERENCE).walk(
s -> s.filter(f -> filterClasses.contains(f.getDeclaringClass())).collect(Collectors.toList()));


--- filter Frame by Class >> get first matching frame ---
--- filter Frame by Class >> get all matching frames ---
[StackWalkerTest.findAllFramesByClass(, StackWalkerTest2.main(]

Updated on: 11-Mar-2020


Kickstart Your Career

Get certified by completing the course

Get Started