Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Class Loader Russian Dolls

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.


1 Answers

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 L may create C by defining it directly or by delegating to another class loader. If L creates C directly, we say that L defines C or, equivalently, that L is the defining loader of C.

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…

like image 177
Holger Avatar answered Mar 29 '26 16:03

Holger