Something like Environment.StackTrace
in .Net.
BTW, Thread.dumpStack()
is not what I want - I want to get the stacktrace back, not print it out.
Something like Environment.StackTrace
in .Net.
BTW, Thread.dumpStack()
is not what I want - I want to get the stacktrace back, not print it out.
You can use Thread
.currentThread().getStackTrace()
That returns an array of StackTraceElement
s that represent the current stack trace of a program.
try {
}
catch(Exception e) {
StackTraceElement[] traceElements = e.getStackTrace();
//...
}
or
Thread.currentThread().getStackTrace()
To get the stack trace of all threads you can either use the jstack utility, JConsole or send a kill -quit signal (on a Posix operating system).
However, if you want to do this programmatically you could try using ThreadMXBean:
ThreadMXBean bean = ManagementFactory.getThreadMXBean();
ThreadInfo[] infos = dumpAllThreads(true, true);
for (ThreadInfo info : infos) {
StackTraceElement[] elems = info.getStackTrace();
// Print out elements, etc.
}
As mentioned, if you only want the stack trace of the current thread it's a lot easier - Just use Thread.currentThread().getStackTrace()
;
Thread.currentThread().getStackTrace();
is fine if you don't care what the first element of the stack is.
new Throwable().getStackTrace();
will have a defined position for your current method, if that matters.
Thread.currentThread().getStackTrace();
is available since JDK1.5.
For an older version, you can redirect exception.printStackTrace()
to a StringWriter()
:
StringWriter sw = new StringWriter();
new Throwable("").printStackTrace(new PrintWriter(sw));
String stackTrace = sw.toString();