如题
public static void main(String[] args) {
caller();
}
public static void caller(){
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(" ClassName:%d\t%s\n", i, s.getClassName());
System.out.format("MethodName:%d\t%s\n", i, s.getMethodName());
System.out.format(" FileName:%d\t%s\n", i, s.getFileName());
System.out.format("LineNumber:%d\t%s\n\n", i, s.getLineNumber());
}
}
获取当前方法名:
public static void main(String[] args) {
String methodName =
(new Throwable()).getStackTrace()[0].getMethodName(); //也可获取文件名,类名等,当前方法index为0,调用者index为1
System.out.println(methodName);
}