在Java静态方法中获取当前类名

更换博客发布地址:http://ihongqiqu.com

静态方法不与特定实例关联,不能引用this,要得到当前类名,没有直接的办法。
通过查资料和试验,可以用下面几种方式:

 1  public static void testGetClassName()
 2      {
 3          // 方法1:通过SecurityManager的保护方法getClassContext()
 4          String clazzName = new SecurityManager()
 5          {
 6              public String getClassName()
 7              {
 8                  return getClassContext()[1].getName();
 9              }
10          }.getClassName();
11          System.out.println(clazzName);
12          // 方法2:通过Throwable的方法getStackTrace()
13          String clazzName2 = new Throwable().getStackTrace()[1].getClassName();
14          System.out.println(clazzName2);
15          // 方法3:通过分析匿名类名称()
16          String clazzName3 = new Object()    {
17              public String getClassName()
18              {
19                  String clazzName = this.getClass().getName();
20                  return clazzName.substring(0, clazzName.lastIndexOf('$'));
21              }
22          }.getClassName();
23          System.out.println(clazzName3);
24      }

分别调用10万次,
    方法1:219ms
    方法2:953ms
    方法3:31ms
比较:
    1)方法1不知有没有什么使用限制?
    2)方法2通过异常机制获取调用栈,性能最差,但能提供其它方法所不具有的功能,还可以获取方法名,行号等等;但这么使用多少有点不太常规;
    3)方法3只是简单分析了一下匿名类的名称,显然要简单多,事实上性能也是最高的;

转载:http://blog.csdn.net/liuwyong11/article/details/5347343

更换博客发布地址:http://ihongqiqu.com

 

原文地址:https://www.cnblogs.com/jingle1267/p/2801262.html