Java——通过线程堆栈信息获取方法调用者的类名或方法名
需求:当出现异常时为了获取出现异常的位置并保存当前方法的调用者的类名或方法名记入日志
技术实现:通过堆栈信息实现。得到的堆栈信息是一个数组,数组角标从0到逐渐增大,最大的是栈顶。
案例代码:对比总结如下,代码中是若干实现与输出结果中间的差别
package com.jhy.getStackTraceDemo; import java.util.Map; public class DemoTest { public static void main(String[] args) { DemoTest demo = new DemoTest(); demo.testOne(); System.out.println("++++++++++++++++++++++++++++++++"); demo.testTwo(); System.out.println("++++++++++++++++++++++++++++++++"); demo.testThree(); } /** * 借助getAllStackTraces */ public void testOne() { StackTraceElement[] stackTraceElement = Thread.getAllStackTraces().get(Thread.currentThread()); for (int i = 0; i < stackTraceElement.length; i++) { System.out.println(Thread.currentThread().getName() + "::::::" + stackTraceElement[i].getClassName() + "." + stackTraceElement[i].getMethodName()); } } /** * 借助currentThread() */ public void testTwo() { StackTraceElement[] stackTraceElement = Thread.currentThread().getStackTrace(); for (int i = 0; i < stackTraceElement.length; i++) { System.out.println(Thread.currentThread().getName() + "::::::" + stackTraceElement[i].getClassName() + "." + stackTraceElement[i].getMethodName()); } } /** * 借助Exception */ public void testThree() { StackTraceElement[] stackTraceElement=new Exception().getStackTrace(); for (int i = 0; i < stackTraceElement.length; i++) { System.out.println(Thread.currentThread().getName() + "::::::" + stackTraceElement[i].getClassName() + "."+ stackTraceElement[i].getMethodName()); } } }
输出结果:
main::::::java.lang.Thread.dumpThreads main::::::java.lang.Thread.getAllStackTraces main::::::com.jhy.getStackTraceDemo.DemoTest.testOne main::::::com.jhy.getStackTraceDemo.DemoTest.main ++++++++++++++++++++++++++++++++ main::::::java.lang.Thread.getStackTrace main::::::com.jhy.getStackTraceDemo.DemoTest.testTwo main::::::com.jhy.getStackTraceDemo.DemoTest.main ++++++++++++++++++++++++++++++++ main::::::com.jhy.getStackTraceDemo.DemoTest.testThree main::::::com.jhy.getStackTraceDemo.DemoTest.main