Is it possible in Java to create a class loader that loads (or more appropriately reloads) itself?
It could initially be loaded by the default classloader. I imagine a system in Java that is able to modify itself as it is running via compilation and loading cycles. If so, you could create many objects that inherit from your Russian-doll loader to dynamically update their logic.
You can reload the code of every class whose qualified name doesn’t start with java. within another ClassLoader, but this doesn’t reload the class. Instead, it creates a new class having the same qualified name but a different defining ClassLoader.
See The Java® Virtual Machine Specification, §5.3. Creation and Loading
A class loader
Lmay createCby defining it directly or by delegating to another class loader. IfLcreatesCdirectly, we say thatLdefinesCor, equivalently, thatLis the defining loader ofC.
…
At run time, a class or interface is determined not by its name alone, but by a pair: its binary name (§4.2.1) and its defining class loader.
So when you define a class with the same qualified name as an existing using a different class loader instance, you are actually creating a new runtime class. Of course, that class might extend ClassLoader and could be used to define again a new class with the same qualified name.
Whether these new classes have identical bytecode, be a modified version or completely unrelated, doesn’t matter.
This is close to how most frameworks supporting reloading of modules work. They create a new class loader (but not a child of the old one), which will “reload” all classes of a module, including the unchanged ones, as technically, it creates a zoo of new unrelated classes which must be linked among each other.
The old classes then have to go out of scope, which requires some care. A class loader can only get garbage collected, if all of its classes are unused. A single instance of one class could prevent its class loader and all of its defined classes from getting garbage collected…
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With