How to show reflection frames of StackFrame in Java 9?

JavaObject Oriented ProgrammingProgramming

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

Example

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());
      }
   }
}

Output

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
raja
Published on 24-Apr-2020 10:22:23
Advertisements