以下代码显示了如何获取线程的堆栈帧。Throwable
对象在创建线程的点处捕获线程的堆栈。参考以下代码 -
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
|
public class Main { public static void main(String[] args) { m1(); } public static void m1() { m2(); } public static void m2() { m3(); } public static void m3() { Throwable t = new Throwable(); StackTraceElement[] frames = t.getStackTrace(); printStackDetails(frames); } public static void printStackDetails(StackTraceElement[] frames) { System.out.println( "Frame count: " + frames.length); for ( int i = 0 ; i < frames.length; i++) { int frameIndex = i; // i = 0 means top frame System.out.println( "Frame Index: " + frameIndex); System.out.println( "File Name: " + frames[i].getFileName()); System.out.println( "Class Name: " + frames[i].getClassName()); System.out.println( "Method Name: " + frames[i].getMethodName()); System.out.println( "Line Number: " + frames[i].getLineNumber()); } } } |
上面的代码生成以下结果。