如何在 Java 9 中显示 StackFrame 的反射框架?

javaobject oriented programmingprogramming更新于 2025/10/23 9:48:17

Java 9 中使用 java.lang.StackWalker  类提供了标准 API。此类旨在通过允许对堆栈框架进行延迟访问来提高效率。在包含实现和/或反射框架的堆栈跟踪中允许使用其他几个选项,并且它可用于调试目的。例如,我们在创建 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<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());
      }
   }
}

输出

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

相关文章


有用资源