Java 9 定義了一個StackWalkerAPI,它提供惰性和幀過濾。 StackWalker物件允許我們遍歷和存取堆疊,並包含一個有用的方法:walk()。此方法為目前執行緒開啟一個StackFrame流,然後將該函數套用到該StackFrame流。我們需要取得StackWalker對象,然後使用StackWalker.getInstance()方法。
在下面的範例中,我們可以列印不同的內容堆疊幀:所有堆疊幀、跳過某些堆疊幀以及使用StackWalkerAPI 限制堆疊框架。 p>
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 = <strong>StackWalker.getInstance</strong>(Set.of(StackWalker.Option.RETAIN_CLASS_REFERENCE, StackWalker.Option.SHOW_HIDDEN_FRAMES), 16); <strong>Stream<StackFrame></strong> stackStream = <strong>StackWalker.getInstance().walk</strong>(f -> f); System.out.println("--- Walk all StackFrames ---"); <strong>List<String></strong> stacks = walkAllStackframes(); System.out.println(stacks); System.out.println("--- Skip some StackFrames ---"); <strong>List<String></strong> stacksAfterSkip = walkSomeStackframes(3); System.out.println(stacksAfterSkip); System.out.println("--- Limit StackFrames ---"); <strong>List<String></strong> stacksByLimit = walkLimitStackframes(3); System.out.println(stacksByLimit); } private List<String> walkAllStackframes() { return <strong>StackWalker.getInstance().walk</strong>(s -> s.map(frame -> "\n" + frame.getClassName() + "/" + frame.getMethodName()).<strong>collect</strong>(Collectors.toList())); } private List<String> walkSomeStackframes(int numberOfFrames) { return <strong>StackWalker.getInstance().walk</strong>(s -> s.map(frame -> "\n" + frame.getClassName() + "/" + frame.getMethodName()).<strong>skip</strong>(numberOfFrames).<strong>collect</strong>(Collectors.toList())); } private List<String> walkLimitStackframes(int numberOfFrames) { return <strong>StackWalker.getInstance().walk</strong>(s -> s.map(frame -> "\n" + frame.getClassName() + "/" + frame.getMethodName()).<strong>limit</strong>(numberOfFrames).<strong>collect</strong>(Collectors.toList())); } } }
<strong>--- Walk all StackFrames --- [ StackWalkerTest$Walker2/walkAllStackframes, StackWalkerTest$Walker2/Method2, StackWalkerTest$Walker2/Method1, StackWalkerTest$Walker2/walk, StackWalkerTest$Walker1/walk, StackWalkerTest/walk, StackWalkerTest/main</strong> <strong>] --- Skip some StackFrames --- [ StackWalkerTest$Walker2/walk, StackWalkerTest$Walker1/walk, StackWalkerTest/walk, StackWalkerTest/main</strong> <strong>] --- Limit StackFrames --- [ StackWalkerTest$Walker2/walkLimitStackframes, StackWalkerTest$Walker2/Method2, StackWalkerTest$Walker2/Method1</strong> <strong>]</strong>
以上是如何使用Java中的StackWalker API列印不同的堆疊幀?的詳細內容。更多資訊請關注PHP中文網其他相關文章!