4

特定の静的メソッドを呼び出したクラス/オブジェクトを見つける方法がJavaにあるかどうか知りたいです。

例:

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

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

クラスUtil.methodから呼び出されたかどうかを確認できますか?Caller

4

1 に答える 1

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());
 }
 ...
}
于 2012-06-13T12:34:43.933 に答える