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.
<strong>public Class<?><!--?--> getCallerClass()</strong>
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>); } }
<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!