在 Java 9 中如何列印 StackFrame API 中的所有屬性?
StackWalker API 是 Java 9 中的一項新功能,它提高了 前身堆疊跟蹤元素的效能。它還可以提供一種在 異常情況下或瞭解 應用程式行為的情況下篩選堆疊元素的方法。在 Java 9 中,訪問堆疊跟蹤的方式非常有限,並且一次性提供整個堆疊資訊。
在下面的示例中,我們需要列印 Stack Frame 中的所有屬性
示例
import java.lang.StackWalker.StackFrame; import java.util.*; import java.util.stream.*; import java.lang.StackWalker.Option; public class AllAttributesTest { public static void main(String args[]) { System.out.println("Java 9 Stack Walker API - Print all attributes in stack frame"); StackWalker newWalker = StackWalker.getInstance(Option.RETAIN_CLASS_REFERENCE); List<StackWalker.StackFrame> stackFrames = newWalker.walk(frames -> frames.limit(1).collect(Collectors.toList())); stackFrames.forEach(test-> { System.out.printf("[Bytecode Index] %d%n", test.getByteCodeIndex()); System.out.printf("[Class Name] %s%n", test.getClassName()); System.out.printf("[Declaring Class] %s%n", test.getDeclaringClass()); System.out.printf("[File Name] %s%n", test.getFileName()); System.out.printf("[Method Name] %s%n", test.getMethodName()); System.out.printf("[Is Native] %b%n", test.isNativeMethod()); System.out.printf("[Line Number] %d%n", test.getLineNumber()); }); } }
輸出
Java 9 Stack Walker API - Print all attributes in stack frame [Bytecode Index] 21 [Class Name] AllAttributesTest [Declaring Class] class AllAttributesTest [File Name] AllAttributesTest.java [Method Name] main [Is Native] false [Line Number] 10
廣告