How to retrieve the current in the Java stack trace information |The Java Debug notes

This article is participating in “Java Theme Month – Java Debug Notes Event”, see < Event link > for more details.

Lift to ask:

How do I get the current stack trace information in Java, as I do in. NET to implement Environment.StackTrace?

I found the Thread.Dumpstack method, but that’s not what I wanted — I wanted to get stack trace information, not print it out.

Answer 1:

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

This returns an array of StackTraceElements that represent the current stack trace information for the program.

Answer 2:

Thread.currentThread().getStackTrace();
Copy the code

If you don’t care about the first element of the stack, this is what you want.

new Throwable().getStackTrace();
Copy the code

If you need to locate the current thread location, use the above method.

Answer 3:

for (StackTraceElement ste : Thread.currentThread().getStackTrace()) {
    System.out.println(ste);
}
Copy the code

Answer 4:

Thread.currentThread().getStackTrace();
Copy the code

The above methods are available starting with JDK1.5.

For older versions, can be the exception. The printStackTrace () redirect to StringWriter () :

StringWriter sw = new StringWriter();
new Throwable("").printStackTrace(new PrintWriter(sw));
String stackTrace = sw.toString();
Copy the code

Answer 5:

You can use Apache’s Commons library:

String fullStackTrace = org.apache.commons.lang3.exception.ExceptionUtils.getStackTrace(e);
Copy the code

Answer 6:

As a comment on the accepted answer (i.e. there is a comment in the first answer, which reads: A one liner to convert the stack trace to a string that works when you don’t have an exception and you aren’t using Apache Arrays.toString(thread.CurrentThread ().getStackTrace()) — Tony)

Arrays.toString(Thread.currentThread().getStackTrace()).replace( ', '.'\n' );
Copy the code

I did not ask how to retrieve strings from stack traces in exceptions. Although I am a big fan of Apache Commons libraries, there is no logical reason to use external libraries when things are as simple as above.

GetAllStackTrace () should be changed from getStackTrace() to getAllStackTrace() to print the entire stack. In this case, make sure to use thread.getallStacktraces (), which provides you with Map . Hotspot will establish safety points for all threads when it needs to safely point to one. Zing can bring individual threads to a safe point without interfering with other threads. Getting stackTrace requires a safe point. Thread.getallstacktraces () gets all stack traces and stops all threads only once. Of course, you have to figure out which stack information you’re actually interested in.) ,stacktraceelement[]>

The original link