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