Home >Java >javaTutorial >How to skip certain classes in StackFrame in Java 9?

How to skip certain classes in StackFrame in Java 9?

WBOY
WBOYforward
2023-09-19 09:13:04546browse

如何在Java 9中跳过StackFrame中的某些类?

StackWalker API Introduced in Java 9, it provides a stack trace snapshot of the current thread at any given point in time and There are ways to walk through it. The advantage of using the StackWalker class compared to Thread::getStackTrace() is that you can filter or skip certain classes and get the instance that declares the class itself and get a short stack trace or Full stack trace instead of extracting the full stack trace itself.

In the following example, we can use java.util.stream.Stream.skip()

strong> 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() {
      <strong>List<StackFrame></strong> framesAfterSkip = StackWalker.getInstance(<strong>StackWalker.Option.RETAIN_CLASS_REFERENCE</strong>).walk((s) ->
s.<strong>skip</strong>(2).collect(<strong>Collectors.toList()</strong>));
      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

<strong>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)]</strong>

The above is the detailed content of How to skip certain classes in StackFrame in Java 9?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete