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