JAVA 開發(fā)之用靜態(tài)方法返回類名的實(shí)例詳解
前言:
最初碰到這個(gè)問題,首先想到的是getClass()方法,
如下嘗試:
1
2
3
4
5
6
|
public static String getClassName() { String className= null ; className= this .getClass().getName(); //靜態(tài)方法中不可訪問變量 this return className; } |
結(jié)果失敗。
偶然發(fā)現(xiàn)有人利用異常處理可以獲得,真是另辟蹊徑,巧妙的很。
實(shí)現(xiàn)代碼:
1
2
3
4
5
6
7
8
9
10
11
|
public static String getClassName() { String className= null ; try { throw new Exception(); } catch (Exception e) { StackTraceElement[] element=e.getStackTrace(); className=element[ 0 ].getClassName(); } return className; } |
以上就是java 獲取類名的方法詳解,如有疑問請(qǐng)留言或者到本站社區(qū)交流討論,感謝閱讀,希望能幫助到大家,謝謝大家對(duì)本站的支持!
原文鏈接:http://blog.csdn.net/54powerman/article/details/1625470