CosminO
CosminO

Reputation: 5226

JAVA: Knowing the Method/Class from where a static method was called

I would like to know if there's a way in java to find out the class/object that called a certain 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 was called from the Caller class?

Upvotes: 4

Views: 240

Answers (1)

tibtof
tibtof

Reputation: 7957

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());
 }
 ...
}

Upvotes: 5

Related Questions