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?
Here is a version that is not deprecated. I modified the original to remove the deprecated functionality.
How about the JCL class loader framework? I have to admit, I haven't used it, but it looks promising.
Usage example:
The best I've found is org.apache.xbean.classloader.JarFileClassLoader which is part of the XBean project.
Here's a short method I've used in the past, to create a class loader from all the lib files in a specific directory
Then to use the classloader, just do:
Here is a quick workaround for Allain's method to make it compatible with newer versions of Java:
Note that it relies on knowledge of internal implementation of specific JVM, so it's not ideal and it's not a universal solution. But it's a quick and easy workaround if you know that you are going to use standard OpenJDK or Oracle JVM. It might also break at some point in future when new JVM version is released, so you need to keep that in mind.
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:
Painful, but there it is.
Another working solution using Instrumentation that works for me. It has the advantage of modifying the class loader search, avoiding problems on class visibility for dependent classes:
Create an Agent Class
For this example, it has to be on the same jar invoked by the command line:
Modify the MANIFEST.MF
Adding the reference to the agent:
I actually use Netbeans, so this post helps on how to change the manifest.mf
Running
The
Launcher-Agent-Class
is only supported on JDK 9+ and is responsible for loading the agent without explicitly defining it on the command line:The way that works on JDK 6+ is defining the
-javaagent
argument:Adding new Jar at Runtime
You can then add jar as necessary using the following command:
I did not find any problems using this on documentation.