在學習java日志體系的源碼時,看到了一段有趣的代碼。
參照java.util.logging.LogRecord 542 private void inferCaller()
編寫一個打印方法調用軌跡的工具類(實際工作中使用Debug)
public class StackTraceUtil { /** * 在想要顯示調用軌跡的方法中加入StackTraceUtil.showStackTrace(); */ public static void showStackTrace(){ JavaLangAccess access= SharedSecrets.getJavaLangAccess(); Throwable throwable = new Throwable(); int depth=access.getStackTraceDepth(throwable); System.out.println("--------------------showStackTrace:sort[Method][Class][LineNumber]--------------------------"); for (int i=depth-1;i>0;i--){//從1開始不顯示當前工具類調用 StackTraceElement ste=access.getStackTraceElement(throwable,i); for(int j=1;j<depth-i;j++){ System.out.print("\t");//縮進 } System.out.println(String.format("%d[%s()][%s][%s]",i,ste.getMethodName(),ste.getClassName(),ste.getLineNumber())); } System.out.println("--------------------showStackTrace:sort[Method][Class][LineNumber]--------------------------"); } }