1. 程式人生 > >類載入時獲取類絕對路徑(靜態程式碼塊獲取類絕對路徑)

類載入時獲取類絕對路徑(靜態程式碼塊獲取類絕對路徑)

    發生的情況: 線上專案CFCA簽章需要一個類似安全證書檔案路徑,在本地只需要獲取弄個靜態變數path="D:/*******"就可以,但是線上就需要從專案路徑下找到這個安全證書的位置.用下面的方法會報空指標異常

        private static String path = null;
static{
path = GetStaticPath.class.getClass().getResource("").getPath();
}



 

    下面的方法也是異常

        private static String path = null;
static{
path = Thread.currentThread().getContextClassLoader().getResource("/").getPath();
}

    下面的方法不會異常

        private static String path = null;

static{
path = GetStaticPath.class.getResource("").getPath();
}

    輸出:/D:/007workspace/learning/bin/learning/



    個人覺得原因是:.class取類的位元組碼檔案,getClass從類的例項物件取類的位元組碼檔案,類載入時還沒有初始化完畢,所以這時候取到得物件為空,Thread.currentThread()取到得物件也為空.

    但是上面的方法.class雖然能取到檔案的路徑,在線上專案就不行了,所以內部類就管用了,參考(

https://my.oschina.net/u/572362/blog/865067)

所以新的方法是

        public static String  JKS_PATH = null;
static {
String path = new Object() {
        public String getPath() {
            return this.getClass().getResource("/").getPath();
        }
}.getPath().substring(1);  
        path=path.replace("classes", "vm"); //去掉class\  
        path+="/anxinsign.jks";
        JKS_PATH = path;
}

OJBK,沒有問題!!!