How to print all attributes in StackFrame API in Java 9?

JavaObject Oriented ProgrammingProgramming

StackWalker API is a new feature in Java 9, and it improves the performance of the predecessor stack track element. It can also provide a way to filter the stack elements in case of exception or to understand application behavior. In Java 9, the way to access the stack trace is very limited and provide the entire stack information at once.

In the below example, we need to print all attributes in Stack Frame 


import java.lang.StackWalker.StackFrame;
import java.util.*;
import java.lang.StackWalker.Option;

public class AllAttributesTest {
   public static void main(String args[]) {
      System.out.println("Java 9 Stack Walker API - Print all attributes in stack frame");
      StackWalker newWalker = StackWalker.getInstance(Option.RETAIN_CLASS_REFERENCE);
      List<StackWalker.StackFrame> stackFrames = newWalker.walk(frames ->  frames.limit(1).collect(Collectors.toList()));
      stackFrames.forEach(test-> {
         System.out.printf("[Bytecode Index] %d%n", test.getByteCodeIndex());
         System.out.printf("[Class Name] %s%n", test.getClassName());
         System.out.printf("[Declaring Class] %s%n", test.getDeclaringClass());
         System.out.printf("[File Name] %s%n", test.getFileName());
         System.out.printf("[Method Name] %s%n", test.getMethodName());
         System.out.printf("[Is Native] %b%n", test.isNativeMethod());
         System.out.printf("[Line Number] %d%n", test.getLineNumber());


Java 9 Stack Walker API - Print all attributes in stack frame
[Bytecode Index] 21
[Class Name] AllAttributesTest
[Declaring Class] class AllAttributesTest
[File Name]
[Method Name] main
[Is Native] false
[Line Number] 10
Published on 31-Mar-2020 12:41:29