How to load Java JAR files dynamically at runtime?
While most of the solutions listed here are either hacks (pre-JDK 9) hard to configure (agents) or just don’t work anymore (post-JDK 9), I find it really surprising that no one mentioned a clearly documented method. You can create a custom system classloader and then you can do whatever you want.
Table of Contents
How to load a JAR file in Java?
Add META-INF/MANIFEST.MF and put it in a JAR file with the agent class: This uses the byte-buddy-agent library to add the agent to the running JVM:
Why is it difficult to load JAR files at runtime?
The reason it’s difficult is security. Classloaders are meant to be immutable; you shouldn’t be able to add classes to it at runtime. In fact, I’m very surprised that it works with the system class loader. Here’s how you do it by creating your own child classloader:
How to load a class dynamically in Java?
Loading a class dynamically is easy. All you need to do is get a ClassLoader and call its loadClass() method. Here’s an example: dynamic class reloading is a bit more challenging. Java’s built-in class loaders always check to see if a class is already loaded before loading it.
Can a library be dynamically loaded by an application?
Making your app able to load libraries dynamically often requires some additional considerations regarding your code and how you implement your app, which, unless you really need the feature, will often make your app more complex rather than less.
What is the sample dynamic code in Java?
The sample dynamic code is a simple class with a static method that prints Hello Nico The name of the class. The file will have the same name and we will also use it to put it as a temporary directory name
Can a custom class loader be created in Java?
You can create a custom system classloader and then you can do whatever you want. No reflection is required and all classes share the same class loader. The classloader must have a constructor that accepts a classloader, which must be set as its parent.