JAVA: Knowledge of the method / class from which the static method was called

I would like to know if there is a way in java to find out the class / object that called the specific static method.

Example:

public class Util{ ... public static void method(){} ... } public class Caller{ ... public void callStatic(){ Util.method(); } ... } 

Can I find out if Util.method is Util.method from the Caller class?

+4
source share
1 answer

You can use Thread.currentThread().getStackTrace() in Util.method .

To get the last call before Util.method , you can do something like this:

 public class Util { ... public static void method() { StackTraceElement[] st = Thread.currentThread().getStackTrace(); //st[0] is the call of getStackTrace, st[1] is the call to Util.method, so the method before is st[2] System.out.println(st[2].getClassName() + "." + st[2].getMethodName()); } ... } 
+5
source

All Articles