Home  >  Article  >  Java  >  In Java 9, when can we use StackWalker.getCallerClass() method?

In Java 9, when can we use StackWalker.getCallerClass() method?

王林
王林forward
2023-09-08 08:45:12809browse

在Java 9中,我们什么时候可以使用StackWalker.getCallerClass()方法?

Java 9 provides an efficient way of stack walking for deferred access, using the StackWalker API to filter stack traces. StackWalker object allows us to traverse and access the stack. This class contains useful methods such as walk(), forEach(), and getCallerClass().

getCallerClass() The method returns the class that called the method. In order to grasp the calling class instance, we need RETAIN_CLASS_REFERENCE when getting the StackWalker instance. RETAIN_CLASS_REFERENCE Retain instances of all classes traversed by StackWalker.

Syntax

<strong>public Class<?><!--?--> getCallerClass()</strong>

Example

import java.lang.StackWalker.Option;

public class StackWalkerTest {
   public static void main(String args[]) {
      StackWalkerTest1.test1();
   }
}

class StackWalkerTest1 {
   protected static void test1() {
      StackWalkerTest2.test2();
   }
}

class StackWalkerTest2 {
   protected static void test2() {
      System.out.println(<strong>StackWalker.getInstance</strong>(<strong>Option.RETAIN_CLASS_REFERENCE</strong>).<strong>getCallerClass()</strong>);
   }
}

Output

<strong>class StackWalkerTest1</strong>

The above is the detailed content of In Java 9, when can we use StackWalker.getCallerClass() method?. 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