Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Java

วิธีพิมพ์ Attributes ทั้งหมดของ StackFrame API ใน Java 9

StackWalker API ใน Java 9 ปรับปรุงประสิทธิภาพ stack trace ให้กรองและเข้าถึง attribute ได้อย่างละเอียด

ตัวอย่างพิมพ์ attributes ทั้งหมด

import java.lang.StackWalker.StackFrame;
import java.util.*;
import java.util.stream.*;
import java.lang.StackWalker.Option;

public class StackFrameAttributes {
    public static void main(String args[]) {
        System.out.println("Java 9 StackWalker - Print all StackFrame attributes");
        
        StackWalker walker = StackWalker.getInstance(Option.RETAIN_CLASS_REFERENCE);
        List frames = walker.walk(s -> s.limit(1).collect(Collectors.toList()));
        
        frames.forEach(frame -> {
            System.out.printf("[Bytecode Index] %d%n", frame.getByteCodeIndex());
            System.out.printf("[Class Name] %s%n", frame.getClassName());
            System.out.printf("[Declaring Class] %s%n", frame.getDeclaringClass());
            System.out.printf("[File Name] %s%n", frame.getFileName());
            System.out.printf("[Method Name] %s%n", frame.getMethodName());
            System.out.printf("[Is Native] %b%n", frame.isNativeMethod());
            System.out.printf("[Line Number] %d%n", frame.getLineNumber());
        });
    }
}

ผลลัพธ์

[Bytecode Index] 21
[Class Name] StackFrameAttributes
[Declaring Class] class StackFrameAttributes
[File Name] StackFrameAttributes.java
[Method Name] main
[Is Native] false
[Line Number] 10