java代码如何获取对象调用者的类名,方法名及行号信息呢?
下文笔者讲述模拟log4j获取对象调用者类名及方法名及行号的方法分享,如下所示
实现思路: 使用Thread.currentThread().getStackTrace() 即可返回当前堆栈信息,然后获取其属性 如下所示: StackTraceElement[] stacks = Thread.currentThread().getStackTrace(); location = "类名:"+stacks[2].getClassName() + "\n函数名:" + stacks[2].getMethodName() + "\n文件名:" + stacks[2].getFileName() + "\n行号:" + stacks[2].getLineNumber() + "";例:
public class InfoTest { public void getInfo(){ String location=""; StackTraceElement[] stacks = Thread.currentThread().getStackTrace(); location = "类名:"+stacks[2].getClassName() + "\n函数名:" + stacks[2].getMethodName() + "\n文件名:" + stacks[2].getFileName() + "\n行号:" + stacks[2].getLineNumber() + ""; System.out.println(location); } } public class Test { public static void main(String[] args) { InfoTest t = new InfoTest(); t.getInfo(); } }
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。