关于Thread.getStrackTrace
说明文档:
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-P1hsEKC4-1587998893106)(C:%5CUsers%5CAdministrator%5CAppData%5CRoaming%5CTypora%5Ctypora-user-images%5Cimage-20200418104635344.png)]
即返回当前线程的堆栈元素
例:
public static void main(String[] args) {
StackTraceElement[] stackTraceElements=Thread.currentThread().getStackTrace();
System.out.println("The stackTraceElements length:"+stackTraceElements.length);
for(int i=0;i<stackTraceElements.length;i++){
System.out.println("\n---the "+i+" element"+"---");
System.out.println("toString:"+stackTraceElements[i].toString());
System.out.println("ClassName:"+stackTraceElements[i].getClassName());
System.out.println("FileName:"+stackTraceElements[i].getFileName());
System.out.println("LineNumber:"+stackTraceElements[i].getLineNumber());
System.out.println("MethodName:"+stackTraceElements[i].getMethodName());
}
printStackInfos();
}
private static void printStackInfos(){
StackTraceElement[] stackTraceElements = Thread.currentThread().getStackTrace();
System.out.println("\nCalled in printStackInfos() method!!!");
System.out.println("The stackTraceElements length:"+stackTraceElements.length);
for(int i =0;i<stackTraceElements.length;i++){
System.out.println("\n---the "+i+" element"+"---");
System.out.println("toString:"+stackTraceElements[i].toString());
System.out.println("ClassName:"+stackTraceElements[i].getClassName());
System.out.println("FileName:"+stackTraceElements[i].getFileName());
System.out.println("LineNumber:"+stackTraceElements[i].getLineNumber());
System.out.println("MethodName:"+stackTraceElements[i].getMethodName());
}
}
输出:
The stackTraceElements length:2
---the 0 element---
toString:java.lang.Thread.getStackTrace(Thread.java:1567)
ClassName:java.lang.Thread
FileName:Thread.java
LineNumber:1567
MethodName:getStackTrace
---the 1 element---
toString:Exchange.main(Exchange.java:10)
ClassName:Exchange
FileName:Exchange.java
LineNumber:10
MethodName:main
Called in printStackInfos() method!!!
The stackTraceElements length:3
---the 0 element---
toString:java.lang.Thread.getStackTrace(Thread.java:1567)
ClassName:java.lang.Thread
FileName:Thread.java
LineNumber:1567
MethodName:getStackTrace
---the 1 element---
toString:Exchange.printStackInfos(Exchange.java:24)
ClassName:Exchange
FileName:Exchange.java
LineNumber:24
MethodName:printStackInfos
---the 2 element---
toString:Exchange.main(Exchange.java:20)
ClassName:Exchange
FileName:Exchange.java
LineNumber:20
MethodName:main
即当调用该函数时:main方法最先入方法栈,然后是printStackInfos,最后是
getStackTrace
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-1Vf3taUo-1587998893107)(C:%5CUsers%5CAdministrator%5CAppData%5CRoaming%5CTypora%5Ctypora-user-images%5Cimage-20200418105436296.png)]