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

4

我想知道在Java中是否有一种方法可以找出调用某个静态方法的类/对象。

例如:

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

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

我能否查找是否从Caller类调用了Util.method方法?


3
类名应该以大写字母开头 :) - Autar
我不知道我从哪里养成了小写的习惯(可能是ActionScript) :) 我在工作中使用大写命名,但我的思维方式已经固定在小写上了。 - CosminO
1个回答

5

你可以在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());
 }
 ...
}

1
我认为提问者想要的不仅仅是类名和方法,还包括对象本身。 - trumank
如果他想要那个,他并没有以那种方式询问 :) - tibtof
我的问题表述可能有误,是的。这才是我真正想要的。不过,有没有办法知道具体的对象呢? :) - CosminO

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接