我想知道在Java中是否有一种方法可以找出调用某个静态方法的类/对象。
例如:
public class Util{
...
public static void method(){}
...
}
public class Caller{
...
public void callStatic(){
Util.method();
}
...
}
我能否查找是否从Caller
类调用了Util.method
方法?
我想知道在Java中是否有一种方法可以找出调用某个静态方法的类/对象。
例如:
public class Util{
...
public static void method(){}
...
}
public class Caller{
...
public void callStatic(){
Util.method();
}
...
}
我能否查找是否从Caller
类调用了Util.method
方法?
你可以在Util.method
中使用Thread.currentThread().getStackTrace()
。
要获取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());
}
...
}