Java中获取运行代码的类名、方法名

以下是案例,已运行通过

 1 package com.hdys;
 2 /*    
 3  * 1.获取当前运行代码的类名,方法名,主要是通过java.lang.StackTraceElement类 
 4  *  
 5  * 2.  
 6  *   [1]获得调用者的方法名, 同new Throwable 
 7  *         String _methodName = new Exception().getStackTrace()[1].getMethodName(); 
 8  *   [0]获得当前的方法名, 同new Throwable 
 9  *         String _thisMethodName = new Exception().getStackTrace()[0].getMethodName(); 
10  *         
11  * 3.获取当前类名的全称和简称,还可以使用 this.getClass()
12  *   (1)获取当前类名的简称
13  *            String simpleClassName = this.getClass().getSimpleName();
14  *   (2)获取当前类名的完整名称
15  *           String className = this.getClass().getName();
16  * */ 
17 public class parent {
18 
19     public static void main(String[] args) {
20         parent t=new parent();
21         System.out.println("---------获取方法名--------------");
22         t.getMethodNameTest();
23         System.out.println("---------获取类名--------------");
24         child c = new child();
25         System.out.println("---------仅获取当前类名--------------");
26         t.getClassNameTest();
27     }
28 
29     //仅获取当前类名
30     public void getClassNameTest(){
31         System.out.println("完整类名:"+this.getClass().getName());
32         System.out.println("简单类名:"+this.getClass().getSimpleName());
33         //System.out.println("父类名 :"+this.getClass().getSuperclass());
34     }
35     
36     //获取方法名
37     public void getMethodNameTest(){
38         String _thisMethodName = new Exception().getStackTrace()[0].getMethodName(); 
39         System.out.println("获得当前的方法名:"+_thisMethodName);
40         
41         String _methodName = new Exception().getStackTrace()[1].getMethodName(); 
42         System.out.println("获得调用者的方法名:"+_methodName);
43     }
44 }
parent .class

 

 1 package com.hdys;
 2 
 3 /*    
 4  * 1.获取当前运行代码的类名,方法名,主要是通过java.lang.StackTraceElement类 
 5  *  
 6  * 2.  
 7  *   [1]获得调用者的类名, 同new Throwable 
 8  *         String _methodName = new Exception().getStackTrace()[1].getClassName(); 
 9  *   [0]获得当前的类名, 同new Throwable 
10  *         String _thisMethodName = new Exception().getStackTrace()[0].getClassName(); 
11  * */ 
12 public class child {
13     
14     public child(){
15         String _className = new Exception().getStackTrace()[1].getClassName(); 
16         System.out.println("获得调用者的类名:"+_className);
17         
18         String _thisClassName = new Exception().getStackTrace()[0].getClassName(); 
19         System.out.println("获得当前类名:"+_thisClassName);
20     }
21 }
child.class

Console端输出结果如下:

---------获取方法名--------------
获得当前的方法名:getMethodNameTest
获得调用者的方法名:main
---------获取类名--------------
获得调用者的类名:com.hdys.parent
获得当前类名:com.hdys.child
---------仅获取当前类名--------------
完整类名:com.hdys.parent
简单类名:parent

 

补充:

strFileName=com.hdys.parent;

strSimpleName=strFileName.substring(strFileName.lastIndexOf("."+1));//获取字符串最后一个.之后的内容

则strSimpleName="parent"

posted @ 2014-07-22 16:42  钟灵.毓秀  阅读(2052)  评论(0编辑  收藏  举报