How to show reflection frames of StackFrame in Java 9?

A standard API has been provided in Java 9 using java.lang.StackWalker class. This class designed to be efficient by allowing lazy access to the stack frames. A couple of other options allow in a stack trace that includes implementation and/or reflection frames, and it can be useful for debugging purposes. For instance, we add SHOW_REFLECT_FRAMES option to StackWalker instance upon creation, so that frames for reflective methods are printed as well.

In the below example, we can able to show reflection frames of 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;

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() {
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

Updated on: 24-Apr-2020


Kickstart Your Career

Get certified by completing the course

Get Started