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

Non-spammers: Thanks for visiting! Please go ahead and leave a comment; I read them all!

Attention SPAMMERS: I review all comments before they get posted, and I REPORT 100% of spam comments to Google as spam! Why not avoid getting your account banned as quickly -- and save us both a little time -- by skipping this comment form and moving on to the next one on your list? Thanks, and I hope you have a great day!