【发布时间】:2011-04-23 21:45:21
【问题描述】:
可能重复:
In Java, how do i find the caller of a method using stacktrace or reflection?
我只是好奇。我有时会请求该功能,但后来我用更多代码解决了它。 (调用类在调用方法时说出它的名字)
【问题讨论】:
-
谢谢你的答案。由于重复,我也可以关闭线程。
可能重复:
In Java, how do i find the caller of a method using stacktrace or reflection?
我只是好奇。我有时会请求该功能,但后来我用更多代码解决了它。 (调用类在调用方法时说出它的名字)
【问题讨论】:
你可以使用“假异常”来做到这一点,尽管这个技巧感觉有点脏。
try {
throw new RuntimeException();
} catch (RuntimeException e) {
System.out.println(e.getStackTrace()[1]);
}
getStackTrace 返回一个由StackTraceElement 对象组成的数组,您可以查看API 以了解您可以使用它们做什么。
【讨论】:
private Class getCallingClass() {
return new SecurityManager() {
protected Class[] getClassContext(){return super.getClassContext();}
}.getClassContext()[2];
}
或
public class Foo {
public static final void main(final String[] args) {
test();
}
private static void test() {
Throwable e = new Throwable();
StackTraceElement[] elements = e.getStackTrace();
System.out.println(elements.length > 1 ? elements[1].toString() : "(no caller)");
}
}
【讨论】:
fillInStackTrace:根据docs,构造函数会为你调用它。