一、利用Thread.currentThread().getStackTrace() 工具类: CodeLine.java
package com.example.codeline;
publicclassCodeLine{
//通过静态方法调用 Thread.currentThread().getStackTrace() 获取当前函数栈时, 已多加了两层方法调用.
/ /Main.main() -->CodeLine.getLineNumber() --> Thread.getStackStrace()
privatestaticint stackIndex = 2;
publicstatic String getFileName(){
return Thread.currentThread().getStackTrace()[originStackIndex].getFileName();
}
publicstatic String getClassName(){
return Thread.currentThread().getStackTrace()[originStackIndex].getClassName();
}
publicstatic String getMethodName(){
return Thread.currentThread().getStackTrace()[originStackIndex].getMethodName();
}
publicstaticintgetLineNumber(){
return Thread.currentThread().getStackTrace()[originStackIndex].getLineNumber();
}
}
测试代码: Main.java:
package com.example.codeline;
public class TestClass
{
public static void main(String[] args)
{
System.out.format(" FileName:\t%s\n", CurrentLineInfo.getFileName());
System.out.format(" ClassName:\t%s\n",CurrentLineInfo.getClassName());
System.out.format("MethodName:\t%s\n",CurrentLineInfo.getMethodName());
System.out.format("LineNumber:\t%s\n\n",CurrentLineInfo.getLineNumber());
}
}
测试输出:
FileName: TestClass.java
ClassName: com.example.codeline.TestClass
MethodName: main
LineNumber: 10
二、利用new Throwable().getStackTrace() 也能得到同样信息
测试代码:
TestClass.java
package com.example.codeline;
public class TestClass
{
public static void main(String[] args)
{
test();
}
public static void test()
{
getCaller();
}
public static void getCaller()
{
StackTraceElement stack[] = (new Throwable()).getStackTrace();
for (int i = 0; i < stack.length; i++)
{
StackTraceElement s = stack[i];
System.out.format(" FileName:%d\t%s\n", i, s.getFileName());
System.out.format(" ClassName:%d\t%s\n", i, s.getClassName());
System.out.format("MethodName:%d\t%s\n", i, s.getMethodName());
System.out.format("LineNumber:%d\t%s\n\n", i, s.getLineNumber());
}
}
}
测试输出:
FileName:0TestClass.java
ClassName:0 com.example.codeline.TestClass
MethodName:0 getCaller
LineNumber:0 17
FileName:1 TestClass.java
ClassName:1 com.example.codeline.TestClass
MethodName:1 test
LineNumber:1 12
FileName:2 TestClass.java
ClassName:2 com.example.codeline.TestClass
MethodName:2 main
LineNumber:2 7