繁体   English   中英

如何从 Java 中的调用方获取堆栈跟踪

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM