views:

8125

answers:

6

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.

+38  A: 

You can use Thread.currentThread().getStackTrace()

That returns an array of StackTraceElements that represent the current stack trace of a program.

jjnguy
StackOverflow makes me lazy :)
ripper234
haha...thanks for asking easy questions!!
jjnguy
Wow, 170 rep. You just scored :)
ripper234
Yup, good question!
jjnguy
Actually I hit the rep cap today, so I didn't make quite that much I don't think.
jjnguy
Got 3 downvotes for some reason.Should 'stupid questions' be downvoted?
ripper234
They should not be downvoted. I dunno why your question would be.
jjnguy
+3  A: 

Silly me, it's Thread.currentThread().getStackTrace();

ripper234
+2  A: 
try {
}
catch(Exception e) {
    StackTraceElement[] traceElements = e.getStackTrace();
    //...
}

or

Thread.currentThread().getStackTrace()
butterchicken
Won't your top example only give you the stack trace relative to the try/catch block?
Dan Monego
indeedy-o it will
butterchicken
+1  A: 

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();

Adamski
+4  A: 
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.

Yishai
+2  A: 
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();
RealHowTo