我想知道在java中是否有办法找出调用某个静态方法的类/对象.
例:
public class Util{
...
public static void method(){}
...
}
public class Caller{
...
public void callStatic(){
Util.method();
}
...
}
Run Code Online (Sandbox Code Playgroud)
我能否知道是否Util.method从Caller课堂上打来电话?
您可以使用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)
| 归档时间: |
|
| 查看次数: |
229 次 |
| 最近记录: |