JAVA:了解调用静态方法的方法/类

Cos*_*inO 4 java

我想知道在java中是否有办法找出调用某个静态方法的类/对象.

例:

public class Util{
 ...
 public static void method(){}
 ...
}

public class Caller{
 ...
 public void callStatic(){
   Util.method();
 }
 ...
}
Run Code Online (Sandbox Code Playgroud)

我能否知道是否Util.methodCaller课堂上打来电话?

tib*_*tof 5

您可以使用Thread.currentThread().getStackTrace()Util.method.

要获得最后一次通话,Util.method您可以执行以下操作:

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());
 }
 ...
}
Run Code Online (Sandbox Code Playgroud)