获取Java class或者jar文件的本地路径

对于常规java class打成jar文件后,要获取它的本地路径,可以用如下方法。

final File f = new File(TestClass.class.getProtectionDomain().getCodeSource().getLocation().getPath());
System.out.println(f.getAbsolutePath());

如果是SpringBoot的启动类,它会被SpringBoot的class loader加载,实际启动jar的时候其实启动的是spring class loader,这个时候如果还想获取jar的本地路径,可以先获取它的loader,再用同样的方法获取路径:

final File f = new File(TestClass.class.getClassLoader().getClass().getProtectionDomain().getCodeSource().getLocation().getPath());
System.out.println(f.getAbsolutePath());
原文地址:https://www.cnblogs.com/pekkle/p/7069892.html