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


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

Updated on: 30-Mar-2020

194 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements