[英]How to get stack trace from the caller in Java
在 Java 中,我想獲取有關如何調用哪些方法的堆棧跟蹤。 我怎樣才能做到這一點?
例如,我的調用堆棧是:
class Example {
public void init() {
func1();
// TODO : now here I want to print the stack trace that it went from:
// func1
// func2
// func3
}
public void func1() {
func2();
}
public void func2() {
func3();
}
public void func3() {
// some code here
}
}
這就是你想要的
class Example {
public void init() {
func1();
// TODO : now here I want to print the stack trace that it went from:
try { throw new Throwable("Debugging") } catch (Throwable t) { t.printStackTrace(); }
// or
System.out.println(Arrays.toString(Thread.currentThread().getStackTrace()));
// func1
// func2
// func3
}
public void func1() {
func2();
}
public void func2() {
func3();
}
public void func3() {
// some code here
}
}
使用 IDE 並使用斷點。 就個人而言,我使用 IntelliJ。 您可以在代碼中添加斷點。 斷點會讓你的程序在被擊中時停止。 此時可以在 IntelliJ 下的 Debugger window 中看到調用堆棧。
IntelliJ 為調試提供了很好的支持,還提供了簡單的教程來開始使用 IntelliJ 調試器工具。
如果要打印堆棧跟蹤,請使用Thread.currentThread.getStackTrace() function。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.