0 votes
1 view
ago in Java by (1.8k points)

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 ClassLoader, 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?

1 Answer

0 votes
ago by (21.7k points)

The ideas arduous is safety. Classloaders are intended to be permanent; you shouldn't be ready to willy-nilly add classes to it at runtime. I'm very shocked that crafts with the system classloader. Here's how you prepare it giving your child classloader:

URLClassLoader child = new URLClassLoader(

        new URL[] {myJar.toURI().toURL()},



Class classToLoad = Class.forName("com.MyClass", true, child);

Method method = classToLoad.getDeclaredMethod("myMethod");

Object instance = classToLoad.newInstance();

Object result = method.invoke(instance);

Raw, but here it's