Java 9定义了一个StackWalker API ,它提供了惰性和帧过滤。StackWalker 的对象允许我们遍历和访问堆栈,并包含一个有用的方法:walk()。此方法为当前线程打开一个StackFrame 流 ,然后将该函数应用于该StackFrame 流。我们需要获取StackWalker 对象,然后使用StackWalker.getInstance() 方法。
在下面的示例中,我们可以使用StackWalker API打印不同的堆栈帧:所有 堆栈帧,跳过 某些堆栈帧并限制 堆栈帧。
import java.lang.StackWalker.StackFrame; import java.util.*; import java.util.stream.*; public class StackWalkerTest { public static void main(String args[]) { new StackWalkerTest().walk(); } private void walk() { new Walker1().walk(); } private class Walker1 { public void walk() { new Walker2().walk(); } } private class Walker2 { public void walk() { Method1(); } void Method1() { Method2(); } void Method2() { StackWalker stackWalker = StackWalker.getInstance(Set.of(StackWalker.Option.RETAIN_CLASS_REFERENCE, StackWalker.Option.SHOW_HIDDEN_FRAMES), 16); Stream<StackFrame> stackStream = StackWalker.getInstance().walk(f -> f); System.out.println("--- Walk all StackFrames ---"); List<String> stacks = walkAllStackframes(); System.out.println(stacks); System.out.println("--- Skip some StackFrames ---"); List<String> stacksAfterSkip = walkSomeStackframes(3); System.out.println(stacksAfterSkip); System.out.println("--- Limit StackFrames ---"); List<String> stacksByLimit = walkLimitStackframes(3); System.out.println(stacksByLimit); } private List<String> walkAllStackframes() { return StackWalker.getInstance().walk(s -> s.map(frame -> "\n" + frame.getClassName() + "/" + frame.getMethodName()).collect(Collectors.toList())); } private List<String> walkSomeStackframes(int numberOfFrames) { return StackWalker.getInstance().walk(s -> s.map(frame -> "\n" + frame.getClassName() + "/" + frame.getMethodName()).skip(numberOfFrames).collect(Collectors.toList())); } private List<String> walkLimitStackframes(int numberOfFrames) { return StackWalker.getInstance().walk(s -> s.map(frame -> "\n" + frame.getClassName() + "/" + frame.getMethodName()).limit(numberOfFrames).collect(Collectors.toList())); } } }
输出结果
--- Walk all StackFrames --- [ StackWalkerTest$Walker2/walkAllStackframes, StackWalkerTest$Walker2/Method2, StackWalkerTest$Walker2/Method1, StackWalkerTest$Walker2/walk, StackWalkerTest$Walker1/walk, StackWalkerTest/walk, StackWalkerTest/main] --- Skip some StackFrames --- [ StackWalkerTest$Walker2/walk, StackWalkerTest$Walker1/walk, StackWalkerTest/walk, StackWalkerTest/main] --- Limit StackFrames --- [ StackWalkerTest$Walker2/walkLimitStackframes, StackWalkerTest$Walker2/Method2, StackWalkerTest$Walker2/Method1]