How to skip certain classes in StackFrame in Java 9?

JavaObject Oriented ProgrammingProgramming

StackWalker API has been introduced in Java 9, and it gives a snapshot of the stack trace of current thread at any given point of time and has methods to walk over it. The advantage of using StackWalker class over Thread::getStackTrace() is to filter or skip certain classes and get the instance of declaring the class itself and get either short stack trace or full stack trace instead of pulling the complete stack trace itself.

In the below example, we can use java.util.stream.Stream.skip() method to skip Stack Frames.

Example

import java.lang.StackWalker.*;
import java.util.Optional;
import java.util.List;
import java.util.stream.Collectors;
import java.lang.StackWalker.StackFrame;

public class StackWalkerSkipTest {
   public static void main(String args[]) {
      new StackWalkerSkipTest().stackWalk();
   }
   private class StackWalker4 {
      public void stackWalk4() {
      List<StackFrame> framesAfterSkip = StackWalker.getInstance(StackWalker.Option.RETAIN_CLASS_REFERENCE).walk((s) ->
s.skip(2).collect(Collectors.toList()));
      System.out.println("Frames after skip : \n" + framesAfterSkip.toString());
   }
}
   public void stackWalk() {
      new StackWalker1().stackWalk1();
   }
   private class StackWalker1 {
      public void stackWalk1() {
         new StackWalker2().stackWalk2();
      }
   }
   private class StackWalker2 {
      public void stackWalk2() {
         new StackWalker3().stackWalk3();
      }
   }
   private class StackWalker3 {
      public void stackWalk3() {
         new StackWalker4().stackWalk4();
      }
   }
}

Output

Frames after skip :
[StackWalkerSkipTest$StackWalker2.stackWalk2(StackWalkerSkipTest.java:29),
StackWalkerSkipTest$StackWalker1.stackWalk1(StackWalkerSkipTest.java:24),
StackWalkerSkipTest.stackWalk(StackWalkerSkipTest.java:19),
StackWalkerSkipTest.main(StackWalkerSkipTest.java:9)]
raja
Published on 24-Apr-2020 09:20:53
Advertisements