Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (3.9k 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
by (46k 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()},

        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);

Raw, but here it's

Related questions

0 votes
1 answer
0 votes
1 answer
asked Oct 28, 2019 in Java by Anvi (10.2k points)
0 votes
1 answer
asked Jul 11, 2019 in Java by Ritik (3.5k points)
0 votes
1 answer
0 votes
1 answer

Browse Categories

...