Dynamically load JAR using URLClassLoader?

I have a program that should be able to dynamically load a JAR at runtime. Looking around, I suppose this uses a URLClassLoader, but I'm not sure how to make it work. The JAR "openup.jar" is in the same directory as the program.

Ideally, I would like to be able to load this JAR without specifying each individual class inside it.

+3
source share
1 answer

What I have successfully used:

@SuppressWarnings("unchecked")
public void addURL(URL u) throws IOException {
    URLClassLoader sysLoader = (URLClassLoader) ThisClass.class.getClassLoader();
    URL urls[] = sysLoader.getURLs();
    for (int i = 0; i < urls.length; i++) {
        if (urls[i].toString().equalsIgnoreCase(u.toString())) {
            return;
        }
    }
    Class sysclass = URLClassLoader.class;
    try {
        Method method = sysclass.getDeclaredMethod("addURL", parameters);
        method.setAccessible(true);
        method.invoke(sysLoader, new Object[] { u });
    } catch (Throwable t) {
        throw new IOException("Error, could not add URL to system classloader");
    }
}

An almost identical solution is really presented in How should I load Jars dynamically at runtime?

+1
source

Source: https://habr.com/ru/post/1784704/


All Articles