Friday, February 22, 2008

Java: Getting a String with the current call stack

Occasionally, in debugging, it can be useful to get the current call stack trace of a program as a String. Here's a simple Java method that will do this:
private static String getCallStackString()
{
 java.io.ByteArrayOutputStream byteArrayOutputStream = new java.io.ByteArrayOutputStream();
 java.io.PrintStream printStream = new java.io.PrintStream(byteArrayOutputStream);
 Throwable throwable = new Throwable("Current call stack:");
 throwable.printStackTrace(printStream);
 return byteArrayOutputStream.toString();
}
Note that this works even in pre-1.4 Java versions, since it doesn't use the getStackTrace method (introduced in Java 1.4). The output of this method is a string along the lines of the following:
java.lang.Throwable: Current call stack:
 at JavaTest.getCallStack(JavaTest.java:36)
 at JavaTest.main(JavaTest.java:24)
A minor variant of this method can be used to get the call stack of an existing Exception:
private static String getCallStackString(Throwable throwable)
{
 java.io.ByteArrayOutputStream byteArrayOutputStream = new java.io.ByteArrayOutputStream();
 java.io.PrintStream printStream = new java.io.PrintStream(byteArrayOutputStream);
 throwable.printStackTrace(printStream);
 return byteArrayOutputStream.toString();
}

No comments:

Post a Comment

Hi spammers! No need to waste your time here; comments are heavily moderated, so if you like, you can save us both a little time and just move on to the next site. :-)

For everyone else: Thanks for visiting! Your comments are more than welcome!