更換博客發布地址: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