How to load JAR files dynamically at Runtime? How to load JAR files dynamically at Runtime? java java

How to load JAR files dynamically at Runtime?


The reason it's hard is security. Classloaders are meant to be immutable; you shouldn't be able to willy-nilly add classes to it at runtime. I'm actually very surprised that works with the system classloader. Here's how you do it making your own child classloader:

URLClassLoader child = new URLClassLoader(        new URL[] {myJar.toURI().toURL()},        this.getClass().getClassLoader());Class classToLoad = Class.forName("com.MyClass", true, child);Method method = classToLoad.getDeclaredMethod("myMethod");Object instance = classToLoad.newInstance();Object result = method.invoke(instance);

Painful, but there it is.


The following solution is hackish, as it uses reflection to bypass encapsulation, but it works flawlessly:

File file = ...URL url = file.toURI().toURL();URLClassLoader classLoader = (URLClassLoader)ClassLoader.getSystemClassLoader();Method method = URLClassLoader.class.getDeclaredMethod("addURL", URL.class);method.setAccessible(true);method.invoke(classLoader, url);


You should take a look at OSGi, e.g. implemented in the Eclipse Platform. It does exactly that. You can install, uninstall, start and stop so called bundles, which are effectively JAR files. But it does a little more, as it offers e.g. services that can be dynamically discovered in JAR files at runtime.

Or see the specification for the Java Module System.