Home >Java >javaTutorial >How to filter stack frames using StackWalker API in Java 9?
StackWalkerAPI provides the flow of information in a stack trace during program execution. This API requires a virtual machine to capture a snapshot of the entire stack and return an array of elements for filtering purposes. We need to use the walk() method to skip, delete and limit stack frames. We can also filter the stack frames by class using the filter() method to get the first matching frame as well as all matching frames.
In the example below, we can use the StackWalker API to filter stack frames.
import java.lang.StackWalker.StackFrame; import java.util.*; import java.util.stream.*; public class StackWalkerFilterTest { public static void main(String args[]) { final <strong>List<Class></strong> filterClasses = new ArrayList<>(); filterClasses.add(StackWalkerFilterTest.class); System.out.println("--- filter Frame by Class >> get first matching frame ---"); <strong>Optional<StackFrame></strong> frameByClass = findFrameByClass(filterClasses); System.out.println(frameByClass.toString()); System.out.println("--- filter Frame by Class >> get all matching frames ---"); <strong>List<StackFrame></strong> framesByClass = findAllFramesByClass(filterClasses); System.out.println(framesByClass); } private static Optional<StackFrame> findFrameByClass(List<Class> filterClasses) { return <strong>StackWalker.getInstance</strong>(StackWalker.Option.<strong>RETAIN_CLASS_REFERENCE</strong>) .<strong>walk</strong>(s -> s.<strong>filter</strong>(f -> filterClasses.contains(f.getDeclaringClass())).<strong>findFirst()</strong>); } private static List<StackFrame> findAllFramesByClass(List<Class> filterClasses) { return StackWalker.getInstance(StackWalker.Option.<strong>RETAIN_CLASS_REFERENCE</strong>).<strong>walk</strong>( s -> s.<strong>filter</strong>(f -> filterClasses.contains(f.getDeclaringClass())).<strong>collect</strong>(Collectors.toList())); } }
<strong>--- 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)]</strong>
The above is the detailed content of How to filter stack frames using StackWalker API in Java 9?. For more information, please follow other related articles on the PHP Chinese website!