- StackTrace用栈的形式保存了方法的调用信息。
- 可用Thread.currentThread().getStackTrace()方法得到当前线程的StackTrace信息,该方法返回的是一个StackTraceElement数组。
- 线程中methodA调用了methodB,那么methodA先入栈methodB再入栈。数组的第一个元素保存的是栈顶元素,最后一个元素保存的栈底元素。正好与调用栈的顺序相反。
- 在StackTraceElement数组下标为2的元素中保存了当前方法的所属文件名,当前方法所属的类名,以及该方法的名字,除此以外还可以获取方法调用的行数。该特性可以用来设计日志模块。
package com.demo.test;
public class StackTraceDemo {
public static void testA() {
testB();
}
public static void testB() {
StackTraceElement[] stackTraceElements = Thread.currentThread().getStackTrace();
System.out.println("-------> StackTraceElement[]");
for (int i = 0; i < stackTraceElements.length; i++) {
System.out.println("-------> " + i);
System.out.println(stackTraceElements[i]);
System.out.println("StackTraceElement.getClassName() => " + stackTraceElements[i].getClassName());
System.out.println("StackTraceElement.getFileName() => " + stackTraceElements[i].getFileName());
System.out.println("StackTraceElement.getLineNumber() => " + stackTraceElements[i].getLineNumber());
System.out.println("StackTraceElement.getMethodName() => " + stackTraceElements[i].getMethodName());
System.out.println("StackTraceElement.isNativeMethod() => " + stackTraceElements[i].isNativeMethod());
}
}
public static String getMethodName() {
StackTraceElement[] stackTraceElements = Thread.currentThread().getStackTrace();
if(stackTraceElements.length > 2) {
return stackTraceElements[2].getMethodName();
}
return null;
}
public static void main(String[] args) {
testA();
System.out.println("\nthis's method name is " + getMethodName());
}
}
输出
-------> StackTraceElement[]
-------> 0
java.lang.Thread.getStackTrace(Unknown Source)
StackTraceElement.getClassName() => java.lang.Thread
StackTraceElement.getFileName() => null
StackTraceElement.getLineNumber() => -1
StackTraceElement.getMethodName() => getStackTrace
StackTraceElement.isNativeMethod() => false
-------> 1
com.demo.test.StackTraceDemo.testB(StackTraceDemo.java:10)
StackTraceElement.getClassName() => com.demo.test.StackTraceDemo
StackTraceElement.getFileName() => StackTraceDemo.java
StackTraceElement.getLineNumber() => 10
StackTraceElement.getMethodName() => testB
StackTraceElement.isNativeMethod() => false
-------> 2
com.demo.test.StackTraceDemo.testA(StackTraceDemo.java:6)
StackTraceElement.getClassName() => com.demo.test.StackTraceDemo
StackTraceElement.getFileName() => StackTraceDemo.java
StackTraceElement.getLineNumber() => 6
StackTraceElement.getMethodName() => testA
StackTraceElement.isNativeMethod() => false
-------> 3
com.demo.test.StackTraceDemo.main(StackTraceDemo.java:32)
StackTraceElement.getClassName() => com.demo.test.StackTraceDemo
StackTraceElement.getFileName() => StackTraceDemo.java
StackTraceElement.getLineNumber() => 32
StackTraceElement.getMethodName() => main
StackTraceElement.isNativeMethod() => false
this's method name is main