1. 程式人生 > >static靜態方法內獲取當前類

static靜態方法內獲取當前類

前景:最近web專案在實現一個在java檔案中讀取專案目錄webcontent下的某一個資原始檔,在static方法中需要獲取資原始檔的路徑,因此需要根據當前的class去獲取到webcontent的路徑。

眾所周知,static修飾的方法中不能使用this關鍵字,因此不能再static方法中使用this.getClass()獲取當前檔案的class,因此換一種思路,編寫一個靜態方法,裡面定義一個普通的內部類,在內部類中使用this.getClass(),然後返回,因此在 static方法需要用到當前class的時候,直接呼叫新編寫的static方法即可。如下

public static void main(String[] args){

Class currentClass = getCurrentClass();

}

private static final Class getCurrentClass(){

return new Object(){
public Class getClassForStatic(){
return this.getClass();
}
}.getClassForStatic();
}