java 獲取對象路徑

java 獲取對象路徑

獲取對象路徑

    public static String getObjectPath(Object obj){
        try {
            return obj.getClass().getProtectionDomain().getCodeSource().getLocation().toURI().getPath();
        } catch (URISyntaxException e) {
            return obj.getClass().getProtectionDomain().getCodeSource().getLocation().getPath();
        }
    }

使用 obj.getClass().getProtectionDomain().getCodeSource().getLocation() 方法後,獲取到的路徑如果有中文,會按照url encode 方式編碼,需要轉換成真實路徑, 加 toURI().getPath() 即可

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章