java-实时打印当前线程的调用堆栈

时间:2022-10-29 12:57:14


java-实时打印当前线程的调用堆栈

/**
* 打印当前线程的调用堆栈
*
*/
void printTrack(){
StackTraceElement[] st = Thread.currentThread().getStackTrace();
if(st==null){
System.out.println("无堆栈...");
return;
}
StringBuffer sbf =new StringBuffer();
for(StackTraceElement e:st){
if(sbf.length()>0){
sbf.append(" <- ");
sbf.append(System.getProperty("line.separator"));
}
sbf.append(java.text.MessageFormat.format("{0}.{1}() {2}"
,e.getClassName()
,e.getMethodName()
,e.getLineNumber()));
}
System.out.println(sbf.toString());
}