天天看點

java中用靜态方法傳回類名

54powerman

最初碰到這個問題,首先想到的是getClass()方法,如下嘗試:

public static String getClassName()

{

 String className=null;

 className=this.getClass().getName();//靜态方法中不可通路變量 this

 return className;

}

結果失敗。

偶然發現有人利用異常處理可以獲得,真是另辟蹊徑,巧妙的很。

 try {

  throw new Exception();

 } catch (Exception e) {

  StackTraceElement[] element=e.getStackTrace();

  className=element[0].getClassName();

 }

記錄下來備用。