我如何在Java中获得当前堆栈跟踪,就像在。net中,你可以做environment。stacktrace ?

我找到了Thread.dumpStack(),但这不是我想要的-我想要得到堆栈跟踪,而不是打印出来。


当前回答

这是一个老帖子,但这是我的解决方案:

Thread.currentThread().dumpStack();

更多信息和更多的方法: http://javarevisited.blogspot.fr/2013/04/how-to-get-current-stack-trace-in-java-thread.html

其他回答

你可以使用Thread.currentThread(). getstacktrace()。

它返回一个stacktraceelement数组,表示程序的当前堆栈跟踪。

我真傻,它是Thread.currentThread().getStackTrace();

对于那些只想获取当前堆栈跟踪到日志中的人来说,我建议:

getLogger().debug("Message", new Throwable());

干杯

托尼,作为对公认答案的评论,给出了似乎是最好的答案,实际上回答了OP的问题:

Arrays.toString(Thread.currentThread().getStackTrace()).replace( ',', '\n' );

... OP没有询问如何从异常的堆栈跟踪中获取字符串。尽管我是Apache Commons的忠实粉丝,但当有像上面这么简单的东西时,使用外部库是没有逻辑理由的。

for (StackTraceElement ste : Thread.currentThread().getStackTrace()) {
    System.out.println(ste + "\n");
}