Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get all jars loaded by a Java application in Java9?

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.

like image 379
Izzel Aliz Avatar asked Oct 02 '17 03:10

Izzel Aliz


1 Answers

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;
    }
}
like image 112
hengyunabc chen Avatar answered Oct 26 '22 23:10

hengyunabc chen