
在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 {
<strong>Method </strong>test1Method = Test1.class.<strong>getDeclaredMethod</strong>("test1", (Class<!--?-->[]) null);
test1Method.<strong>invoke</strong>(null, (Object[]) null);
}
}
class Test1 {
protected static void test1() {
Test2.test2();
}
}
class Test2 {
protected static void test2() {
<strong>// show reflection methods</strong>
<strong>List<StackFrame></strong> stack = <strong>StackWalker.getInstance</strong>(Option.<strong>SHOW_REFLECT_FRAMES</strong>).walk((s) -> s.collect(Collectors.toList()));
for(<strong>StackFrame </strong>frame : stack) {
System.out.println(frame.<strong>getClassName()</strong> + " " + frame.<strong>getLineNumber()</strong> + " " + frame.<strong>getMethodName()</strong>);
}
}
}<strong>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</strong>
以上就是如何在Java 9中显示StackFrame的反射框架?的详细内容,更多请关注php中文网其它相关文章!
java怎么学习?java怎么入门?java在哪学?java怎么学才快?不用担心,这里为大家提供了java速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号