How to load an external . jar in Java 11

Asked

Viewed 39 times

0

It is possible to load a .jar external in the Classloader of Java 11?

I can do this in version 8 of Java, but from 9 the method for this ends up being broken (because it is considered a security fault and Classloader works different).

In Java 8 the method for this (using Reflection) is:

public static void addClassPathURL(File jar) throws Exception {
    Method method = URLClassLoader.class.getDeclaredMethod("addURL", new Class[] { URL.class });
    method.setAccessible(true);
    method.invoke(Thread.currentThread().getContextClassLoader(), new Object[] { jar.toURI().toURL() });
}

If possible, can you give me some example here?

1 answer

0


Try to run as follows using the getSystemClassLoader:

public static void addClassPathURL(File jar) throws Exception {

    ClassLoader classLoader = ClassLoader.getSystemClassLoader();
    try {
        Method method = classLoader.getClass().getDeclaredMethod("addURL", URL.class);
        method.setAccessible(true);
        method.invoke(classLoader, jar.toURI().toURL());
    } catch (NoSuchMethodException e) {
        Method method = classLoader.getClass()
                .getDeclaredMethod("appendToClassPathForInstrumentation", String.class);
        method.setAccessible(true);
        method.invoke(classLoader, jar.getPath());
    }

}
  • Thank you very much! I’ve been looking for this for a long time, for a project I’ve been doing. Now I’ll be able to update it to Java 11+. I went to a lot of places looking for this, and I didn’t think, I just found Java 8.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.