JAVA 获取类名,函数名

时间:2015-05-15 10:21:53   收藏:0   阅读:144

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

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

 

 

 

 
评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!