可能重複:
In Java, how do i find the caller of a method using stacktrace or reflection?我可以確定誰在調用函數或實例化Java中的類嗎?
我只是好奇。我有時要求這個功能,但後來我用更多的代碼解決了這個問題。 (呼叫類在調用方法時說出它的名字)
可能重複:
In Java, how do i find the caller of a method using stacktrace or reflection?我可以確定誰在調用函數或實例化Java中的類嗎?
我只是好奇。我有時要求這個功能,但後來我用更多的代碼解決了這個問題。 (呼叫類在調用方法時說出它的名字)
你可以使用'假異常'來做到這一點,即使這個技巧感覺有點骯髒。
try {
throw new RuntimeException();
} catch (RuntimeException e) {
System.out.println(e.getStackTrace()[1]);
}
getStackTrace
返回StackTraceElement
對象的數組,你可以檢查API看到你可以與他們做什麼。
你不需要扔掉它,查看我的回答 – 2010-10-11 16:18:47
@ org.life.java謝謝,很高興知道 – 2010-10-11 16:26:37
private Class getCallingClass() {
return new SecurityManager() {
protected Class[] getClassContext(){return super.getClassContext();}
}.getClassContext()[2];
}
OR
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](http:/ /download.oracle.com/javase/1.4.2/docs/api/java/lang/Throwable.html#Throwable%28%29),構造函數會爲你調用它。 – casablanca 2010-10-11 16:20:48
@casablanca耶同意 – 2010-10-11 16:23:53
THX的答案。由於重複,線程關閉也很好。 – OneWorld 2010-10-11 19:36:27