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

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


当前回答

try {
}
catch(Exception e) {
    StackTraceElement[] traceElements = e.getStackTrace();
    //...
}

or

Thread.currentThread().getStackTrace()

其他回答

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

数组的最后一个元素表示堆栈的底部,这是序列中最近的方法调用。

A StackTraceElement has getClassName(), getFileName(), getLineNumber() and getMethodName().

循环遍历StackTraceElement并获得所需的结果。

for (StackTraceElement ste : stackTraceElements ) 
{
    //do your stuff here...
}

如果希望检查进程的当前调用堆栈,可以使用jstack实用程序。

Usage:
    jstack [-l] <pid>
        (to connect to running process)
    jstack -F [-m] [-l] <pid>
        (to connect to a hung process)
    jstack [-m] [-l] <executable> <core>
        (to connect to a core file)
    jstack [-m] [-l] [server_id@]<remote server IP or hostname>
        (to connect to a remote debug server)

Options:
    -F  to force a thread dump. Use when jstack <pid> does not respond (process is hung)
    -m  to print both java and native frames (mixed mode)
    -l  long listing. Prints additional information about locks
    -h or -help to print this help message

也许你可以试试这个:

catch(Exception e)
{
    StringWriter writer = new StringWriter();
    PrintWriter pw = new PrintWriter(writer);
    e.printStackTrace(pw);
    String errorDetail = writer.toString();
}

字符串'errorDetail'包含了堆栈跟踪。

在android上,一个更简单的方法是使用这个:

import android.util.Log;
String stackTrace = Log.getStackTraceString(exception); 

另一个解决方案(只有35 - 31个字符):

new Exception().printStackTrace();   
new Error().printStackTrace();