Java 确定当前调用堆栈(用于诊断目的)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/706292/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 18:34:21  来源:igfitidea点击:

Determining Current Call Stack (For Diagnostic Purposes)

javastack-trace

提问by Thilo-Alexander Ginkel

For diagnostic purposes I sometimes need to store the call stack that lead to a given state transition (such as granting a lock, committing a transaction, etc.) so that when something goes wrong later I can find out who originally triggered the state transition.

出于诊断目的,我有时需要存储导致给定状态转换(例如授予锁、提交事务等)的调用堆栈,以便以后出现问题时我可以找出最初触发状态转换的人。

Currently, the only way I am aware of to retrieve the call stack looks like the following code snippet, which I consider terribly ugly:

目前,我所知道的检索调用堆栈的唯一方法类似于以下代码片段,我认为它非常难看:

StackTraceElement[] cause;
try {
  throw new Exception();
} catch (Exception e) {
  cause = e.getStackTrace();
}

Does somebody know of a better way to accomplish this?

有人知道实现这一目标的更好方法吗?

采纳答案by bruno conde

I think you can get the same thing with:

我认为你可以得到同样的东西:

StackTraceElement[] cause = Thread.currentThread().getStackTrace();

回答by Michael Myers

Well, you can improve it slightly by not actually throwing the exception.

好吧,您可以通过不实际抛出异常来稍微改进它。

Exception ex = new Exception();
ex.fillInStackTrace();
StackTraceElement[] cause = ex.getStackTrace();

Actually, I just checked: the constructor calls fillInStackTrace()already. So you can simplify it to:

实际上,我刚刚检查过:构造函数fillInStackTrace()已经调用了。因此,您可以将其简化为:

StackTraceElement[] cause = new Exception().getStackTrace();

This is actually what Thread.getStackTrace()does if it's called on the current thread, so you might prefer using it instead.

Thread.getStackTrace()如果在当前线程上调用它,这实际上是什么,因此您可能更喜欢使用它。

回答by Edward Anderson

If you want it as a String and use Apache Commons:

如果您希望将其作为字符串并使用 Apache Commons:

org.apache.commons.lang.exception.ExceptionUtils.getFullStackTrace(new Throwable())