How to skip certain classes in StackFrame in Java 9?

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 method to skip Stack Frames.


import java.lang.StackWalker.*;
import java.util.Optional;
import java.util.List;
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) ->
      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();


Frames after skip :