
在Java 9中提供了一个标准的API,使用java.lang.StackWalker 类。这个类被设计成高效的,通过允许延迟访问堆栈帧。另外,还有几个选项可以在堆栈跟踪中包含实现和/或反射帧,这对于调试目的非常有用。例如,我们在创建StackWalker实例时添加SHOW_REFLECT_FRAMES 选项,以便打印反射方法的帧。
在下面的示例中,我们可以显示StackFrame的反射帧
示例
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() {
// show reflection methods
List 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());
}
}
}输出
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











