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

JavaObject Oriented ProgrammingProgramming

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.

Example

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

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

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

      System.out.println("--- filter Frame by Class >> get all matching frames ---");
      List<StackFrame> framesByClass = findAllFramesByClass(filterClasses);
      System.out.println(framesByClass);
   }
   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()));
   }
}

Output

--- filter Frame by Class >> get first matching frame ---
Optional[StackWalkerTest.findFrameByClass(StackWalkerTest.java:20)]
--- filter Frame by Class >> get all matching frames ---
[StackWalkerTest.findAllFramesByClass(StackWalkerTest.java:23), StackWalkerTest2.main(StackWalkerTest.java:15)]
raja
Published on 11-Mar-2020 14:41:48
Advertisements