When can we use StackWalker.getCallerClass() method in Java 9?

JavaObject Oriented ProgrammingProgramming

Java 9 has provided an efficient way of stack walking for lazy access, filtering stack trace using StackWalker API. An object of StackWalker can allow us to traverse and access to stacks. This class contains some useful methods like walk(), forEach(), and getCallerClass().

The getCallerClass() method returns the class that invokes the method that calls this method. To get hold of calling class instance, we need RETAIN_CLASS_REFERENCE while getting StackWalker instance. RETAIN_CLASS_REFERENCE retains an instance of all classes walked by StackWalker.

Syntax

public Class<?> getCallerClass()

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(StackWalker.getInstance(Option.RETAIN_CLASS_REFERENCE).getCallerClass());
   }
}

Output

class StackWalkerTest1
raja
Published on 30-Mar-2020 15:26:41
Advertisements