This article is participating in the Java Theme Month – Java Debug Notes Event, see the event link for details

“How do I get the current stack trace in Java?

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

I found thread.Dumpstack () but that’s not what I wanted – I wanted to retrieve the stack trace information, not print it out.

Answer:


A lot of knowledge points, really need to write out will master ! ! !   \color{purple} a lot of knowledge points, really need to write out just can master!! {~}

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

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

Answer:

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

If you don’t care about the first element of the stack, that’s fine.

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

If important, the location is defined for your current method.

Answer:


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

Available as of JDK1.5.

For the older version, you can redirect the exception. PrintStackTrace () to a StringWriter () :

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

The article translated from yl2gl72eozkinivz3vc6swkesy – ac4c6men2g7xr2a – translate. Translate. Goog/questions / 1…

The author suggests: I care about my stack information when I have memory overflow or memory leak. If in Windows, I can directly open jVisualVM under the bin file. If in Linux, I can use Jmap to see the most occupied heap, jStack to see the stack information of threads, and can also use Arthas to analyze.


Welcome to my column S t a c k O v e r F l o w . I select the best questions and answers and test them frequently in interviews ! ! !   \color{red} Welcome to my column StackOverFlow, I will filter the quality of the interview test!! {~}


There are the latest and elegant ways to do this, and I will write my thoughts on this q&A at the end of the article \color{red} has the latest, elegant implementation, and I will also write my opinion on this question at the end of the article {~}

Thank you for reading this, if this article is well written and if you feel there is something to it

Ask for a thumbs up 👍 ask for attention ❤️ ask for share 👥 for 8 abs I really very useful!!

If there are any mistakes in this blog, please comment, thank you very much! ❤ ️ ❤ ️ ❤ ️ ❤ ️