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()
即可