For some reason, I want to get all loaded jars' file path. Previously on java8, I have done this by using
for (java.net.URL url : ((java.net.URLClassLoader) A.class.getClassLoader()).getURLs()) {
try {
String path = url.toString();
if (path.startsWith("file:/"))
path = path.substring(6);
path = java.net.URLDecoder.decode(path, "UTF-8");
} catch (Exception e) {
e.printStackTrace();
}
}
But in Java 9, the SystemClassLoader connot cast to URLClassLoader.
Currently I am using SomeClass.class.getProtectDomain().getCodeSource().getLocation()
, but this costs much, so I am here asking for some more gentle way to do this.
Try this:
/**
*
* @author hengyunabc 2017-10-12
*
*/
public class ClassLoaderUtils {
@SuppressWarnings({ "restriction", "unchecked" })
public static URL[] getUrls(ClassLoader classLoader) {
if (classLoader instanceof URLClassLoader) {
return ((URLClassLoader) classLoader).getURLs();
}
// jdk9
if (classLoader.getClass().getName().startsWith("jdk.internal.loader.ClassLoaders$")) {
try {
Field field = Unsafe.class.getDeclaredField("theUnsafe");
field.setAccessible(true);
Unsafe unsafe = (Unsafe) field.get(null);
// jdk.internal.loader.ClassLoaders.AppClassLoader.ucp
Field ucpField = classLoader.getClass().getDeclaredField("ucp");
long ucpFieldOffset = unsafe.objectFieldOffset(ucpField);
Object ucpObject = unsafe.getObject(classLoader, ucpFieldOffset);
// jdk.internal.loader.URLClassPath.path
Field pathField = ucpField.getType().getDeclaredField("path");
long pathFieldOffset = unsafe.objectFieldOffset(pathField);
ArrayList<URL> path = (ArrayList<URL>) unsafe.getObject(ucpObject, pathFieldOffset);
return path.toArray(new URL[path.size()]);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
return null;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With