How can I get the current stack trace in Java? How can I get the current stack trace in Java? java java

How can I get the current stack trace in Java?


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

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


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.


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