Allain Lalonde Allain Lalonde - 1 year ago 89
Java Question

How should I load Jars dynamically at runtime?

Why is it so hard to do this in Java? If you want to have any kind of module system you need to be able to load jars dynamically. I'm told there's a way of doing it by writing your own

, but that's a lot of work for something that should (in my mind at least) be as easy as calling a method with a jar file as its argument.

Any suggestions for simple code that does this?

Answer Source

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 (myJar.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.