API chuẩn được cung cấp trong Java 9 dùng lớp java.lang.StackWalker. Lớp này thiết kế hiệu quả bằng cách cho phép lazy access đến stack frame. Một vài tùy chọn khác cho phép stack trace bao gồm implementation và/hoặc reflection frames, hữu ích cho debugging. Ví dụ, thêm tùy chọn SHOW_REFLECT_FRAMES vào instance StackWalker khi tạo, để frame của phương thức reflection cũng được in.
Ví dụ dưới hiển thị reflection frame của StackFrame.
Ví dụ
import java.lang.StackWalker.Option;
import java.lang.StackWalker.StackFrame;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.List;
import java.util.stream.Collectors;
public class ReflectionFrameTest {
public static void main(String args[]) throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
Method test1Method = Test1.class.getDeclaredMethod("test1", (Class[]) null);
test1Method.invoke(null, (Object[]) null);
}
}
class Test1 {
protected static void test1() {
Test2.test2();
}
}
class Test2 {
protected static void test2() {
// hiển thị reflection methods
List<StackFrame> stack = StackWalker.getInstance(Option.SHOW_REFLECT_FRAMES).walk(s -> s.collect(Collectors.toList()));
for (StackFrame frame : stack) {
System.out.println(frame.getClassName() + " " + frame.getLineNumber() + " " + frame.getMethodName());
}
}
}
Kết quả
Test2 22 test2 Test1 16 test1 jdk.internal.reflect.NativeMethodAccessorImpl -2 invoke0 jdk.internal.reflect.NativeMethodAccessorImpl 62 invoke jdk.internal.reflect.DelegatingMethodAccessorImpl 43 invoke java.lang.reflect.Method 564 invoke ReflectionFrameTest 11 main