我正在尝试获取 Java 中线程的当前堆栈跟踪。我探索了以下方法:
在 Java 中打印当前线程的堆栈跟踪的最简单方法之一是使用 java.lang.Thread 类中的 dumpStack() 方法
打印堆栈跟踪的另一种方法是使用 Throwable 类的 printStackTrace() 方法
还有其他方法可以让我们更有效地获取 Java 中线程的当前堆栈跟踪吗?
下面是我设计的课程..
public class StackTraceExample
{
private static final Logger logger = Logger.getLogger(StringReplace.class.getName());
public static void main(String args[])
{
//calling a method to print stack trace further down
first();
}
public static void first()
{
second();
}
private static void second()
{
third();
}
private static void third()
{
//If you want to print stack trace on console than use dumpStack() method
System.err.println("Stack trace of current thread using dumpStack() method");
Thread.currentThread().dumpStack();
//This is another way to print stack trace from current method
System.err.println("Printing stack trace using printStackTrace() method of Throwable ");
new Throwable().printStackTrace();
//If you want stack trace as StackTraceElement in program itself than
//use getStackTrace() method of Thread class
StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
//Once you get StackTraceElement you can also print it to console
System.err.println("displaying Stack trace from StackTraceElement in Java");
for(StackTraceElement st : stackTrace)
{
// System.err.println(st);
}
}
}
输出 :-
Stack trace of current thread using dumpStack() method
java.lang.Exception: Stack trace
at java.lang.Thread.dumpStack(Thread.java:1249)
at test.StringReplace.third(StringReplace.java:38)
at test.StringReplace.second(StringReplace.java:31)
at test.StringReplace.first(StringReplace.java:27)
at test.StringReplace.main(StringReplace.java:23)
Printing stack trace using printStackTrace() method of Throwable
java.lang.Throwable
at test.StringReplace.third(StringReplace.java:42)
at test.StringReplace.second(StringReplace.java:31)
at test.StringReplace.first(StringReplace.java:27)
at test.StringReplace.main(StringReplace.java:23)
displaying Stack trace from StackTraceElement in Java