It is possible to load and reload classes at runtime in Java, though it is not as straightforward as one might have hoped. This text will explain when and how you can load and reload classes in Java.
The ClassLoader
All classes in a Java application are loaded using some subclass ofjava.lang.ClassLoader
. Loading classes dynamically must therefore also be done using a java.lang.ClassLoader
subclass.
When a class is loaded, all classes it references are loaded too. This class loading pattern happens recursively, until all classes needed are loaded. This may not be all classes in the application. Unreferenced classes are not loaded until the time they are referenced.
Class Loading
The steps a given class loader uses when loading classes are:
- Check if the class was already loaded.
- If not loaded, ask parent class loader to load the class.
- If parent class loader cannot load class, attempt to load it in this class loader.
When you implement a class loader that is capable of reloading classes you will need to deviate a bit from this sequence. The classes to reload should not be requested loaded by the parent class loader.
Dynamic Class Loading
Loading a class dynamically is easy. All you need to do is to obtain a ClassLoader
and call its loadClass()
method