JAVA 获取类名,函数名

获取以下获取方法所在函数的相关信息

1.获取当前函数名:Thread.currentThread().getStackTrace()[1].getMethodName();

2.获取当前类名:Thread.currentThread().getStackTrace()[1].getClassName();

3.获取当前类的文件名:Thread.currentThread().getStackTrace()[1].getFileName();  

获取调用方法的所在函数的相关信息

1.获取当前函数名:Thread.currentThread().getStackTrace()[2].getMethodName();

2.获取当前类名:Thread.currentThread().getStackTrace()[2].getClassName();

3.获取当前类的文件名:Thread.currentThread().getStackTrace()[2].getFileName();  

Demo:

这是获取方法

 1 public class NameProxy {
 2 
 3     public static void nowMethod() {
 4         String clazz = Thread.currentThread().getStackTrace()[1].getClassName();
 5         String method = Thread.currentThread().getStackTrace()[1]
 6                 .getMethodName();
 7         System.out.println("class name: " + clazz + " Method Name " + method);
 8     }
 9 
10     public static void parentMethod() {
11         String clazz = Thread.currentThread().getStackTrace()[2].getClassName();
12         String method = Thread.currentThread().getStackTrace()[2]
13                 .getMethodName();
14         System.out.println("class name: " + clazz + " Method Name " + method);
15     }
16 
17 }

Test:

1 public class MethodName {
2 
3     @Test
4     public void showMethodName() {
5         LogProxyName.nowMethod();
6         LogProxyName.parentMethod();
7     }
8 
9 }

显示结果:

1 class name: com.XXX.name.NameProxy Method Name nowMethod
2 class name: com.XXX.name.MethodName Method Name showMethodName
 
原文地址:https://www.cnblogs.com/fengzhentian/p/4505157.html