I have a program which needs to be able to dynamically load JARs at runtime - after looking around I beleive this uses URLClassLoader, but I'm not sure how to get it to 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 having to specify each individual class inside it.
What I 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 indeed presented in How should I load Jars dynamically at runtime?