Sub topic 13
Writing a custom class loader
This chapter assumes you know how parent delegation works and the difference between loading, linking and initialization. It also assumes you can compile and run Java from the command line. Here you will write a loader, load a class from a directory the application classpath doesn't contain, and see what the JVM does with the result.
What a class loader has to do
A class loader turns a class name into a Class object. The JVM calls loadClass(String name) on a loader. That method implements the lookup policy. The only step that creates a class from bytes is defineClass. It parses the bytes, checks the format and registers the class under the calling loader as its defining loader.
The default loadClass does three things in order:
- It calls
findLoadedClass(name)to see whether this loader has already defined the class. - It asks the parent loader, or the bootstrap loader if there is no parent.
- If the parent fails with
ClassNotFoundException, it callsfindClass(name).
The default findClass always throws ClassNotFoundException. A custom loader overrides findClass to supply bytes from somewhere else: a directory, a JAR, a network stream, a database or generated code.
A minimal loader
The loader below maps a class name to a file under a root directory. It passes the parent to super(parent) so the default delegation keeps working.
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
public class DirClassLoader extends ClassLoader {
private final Path root;
public DirClassLoader(Path root, ClassLoader parent) {
super(parent);
this.root = root;
}
@Override
protected Class<?> findClass(String name) throws ClassNotFoundException {
Path file = root.resolve(name.replace('.', '/') + ".class");
try {
byte[] bytes = Files.readAllBytes(file);
return defineClass(name, bytes, 0, bytes.length);
} catch (IOException e) {
throw new ClassNotFoundException(name, e);
}
}
}The BytesClassLoader from the earlier example works the same way, except that it holds one class's bytes in memory instead of reading a file. Both follow the same rule: override findClass, and throw ClassNotFoundException when the loader can't supply the class. The default loadClass uses that exception to move on to the next step.
Trying it
Create a class that the application classpath will not contain:
public class Greeter {
public String hello() {
return "Hello from " + getClass().getClassLoader().getClass().getSimpleName();
}
}Then create a launcher that uses two separate loaders over the same directory:
import java.nio.file.Path;
public class LoadPlugin {
public static void main(String[] args) throws Exception {
Path dir = Path.of(args[0]);
ClassLoader parent = LoadPlugin.class.getClassLoader();
ClassLoader a = new DirClassLoader(dir, parent);
ClassLoader b = new DirClassLoader(dir, parent);
Class<?> ca = a.loadClass("Greeter");
Class<?> cb = b.loadClass("Greeter");
System.out.println(ca.getClassLoader() == a);
System.out.println(ca == cb);
Object greeter = ca.getDeclaredConstructor().newInstance();
System.out.println(ca.getMethod("hello").invoke(greeter));
System.out.println(cb.isInstance(greeter));
}
}Compile Greeter into its own directory and everything else into another. Then run with only the second directory on the classpath:
$ mkdir plugins out
$ javac -d plugins Greeter.java
$ javac -d out DirClassLoader.java LoadPlugin.java
$ java -cp out LoadPlugin plugins
true
false
Hello from DirClassLoader
falseThe output shows several things:
Greeteris not on the classpath, so the application loader fails andfindClassruns. The first line confirms thatais the defining loader.- The same
.classfile loaded throughaandbgives two differentClassobjects. A class's identity is its name plus its defining loader. - An instance created from
cais not an instance ofcb. Casting between them throwsClassCastExceptioneven though the names are identical.
Why you override findClass, not loadClass
Overriding findClass keeps the delegation rules intact. Core classes such as java.lang.String always come from the bootstrap loader, so nobody can slip in a replacement through your loader.
Overriding loadClass lets you change the policy, for example to look in your own source first. Servlet containers and plugin systems do this so that each web application or plugin can bring its own library versions. It also takes on responsibilities the default method handled for you.
- Check
findLoadedClassfirst. CallingdefineClasstwice for the same name in the same loader throwsLinkageError(duplicate class definition). - Delegate the platform packages. If you define
java.*classes yourself,defineClassthrowsSecurityException("Prohibited package name"). Classes fromjavax.*and other platform modules should also go to the parent, or you will get mismatched types. - Use the locking support. Concurrent loading of the same name needs
getClassLoadingLock(name). If you don't need concurrency, don't think about it. If you do, callregisterAsParallelCapable()in a static initializer.
Which loader resolves dependencies
When Greeter references another class, say Helper, the JVM asks Greeter's defining loader to load Helper. It doesn't ask the loader that happens to be running the code. This is why a.loadClass("Greeter") also finds Helper in the same directory. It is also why Greeter can see classes from the parent chain, such as java.lang.String or your launcher's own classes, but the launcher can't name Greeter directly. The launcher's loader is the parent, and delegation only goes upward.
To use a class that was loaded dynamically, the usual approach is:
- Define an interface in a class both sides can see, loaded by the parent.
- Have the plugin class implement that interface.
- Load the plugin through reflection, then cast the instance to the shared interface.
public interface Plugin {
String name();
}If both the host and the plugin loader loaded Plugin separately, the cast would fail. With the interface only on the host side, the plugin's loader delegates to the parent and gets the host's copy, so the cast succeeds.
Loading is not initializing
loadClass returns a loaded class. It doesn't link it and, more importantly, it doesn't run static initializers. Initialization occurs at first active use, or when you ask for it explicitly:
Class<?> c = Class.forName("Greeter", true, loader);With false as the second argument, Class.forName loads without initializing. In the example above, newInstance() triggers initialization of Greeter.
Errors a custom loader produces
| Error | Typical cause |
|---|---|
| `ClassNotFoundException` | `findClass` found no bytes, or the name was wrong. It is thrown by explicit lookups such as `loadClass` and `Class.forName`. |
| `NoClassDefFoundError` | The class was present at compile time but its loader can't find it at run time. It can also mean `defineClass` was given a name that doesn't match the bytes ("wrong name"). |
| `ClassFormatError` | The bytes are not a valid class file, for example a truncated file or a version this JVM can't read (`UnsupportedClassVersionError`). |
| `LinkageError` | The same name was defined twice in one loader. |
| `ClassCastException` | Two loaders defined distinct classes with the same name. |
| `SecurityException` | The code tried to define a class in a prohibited package such as `java.*`. |
Naming and unloading
Since Java 9 you can give a loader a name with the constructor ClassLoader(String name, ClassLoader parent). The name appears in stack traces and logs, which helps when several loaders look alike.
A class can be unloaded only when its defining loader becomes unreachable. That means no references to the loader, to any class it defined, or to any instance of those classes. Plugin systems rely on this to reload code: drop the old loader, create a new one, and let the garbage collector reclaim the old classes. Leaks happen when something long-lived, such as a thread, a static field in a parent-loaded class, or a ThreadLocal, still holds an object from the old loader.
Summary of rules
- Extend
ClassLoaderand overridefindClass. LeaveloadClassalone unless you need a different lookup policy. - Always pass a parent, and be deliberate about which one.
- Share types between the host and the dynamically loaded code through interfaces loaded by the parent.
- Don't expect
loadClassto run static initializers.
Exercise
In the LoadPlugin example, you copy Greeter.class into the out directory too and run java -cp out LoadPlugin plugins again. What does ca.getClassLoader() == a print, and why?
Show answer
It prints false. The application loader is the parent of a and now finds Greeter on the classpath. Because loadClass asks the parent first, findClass is never called, and the defining loader of Greeter is the application loader.
Exercise
A plugin class implements an interface Plugin, and both the plugin directory and the host classpath contain a Plugin.class. The host casts the loaded instance to Plugin and gets a ClassCastException. Name the cause and give two ways to fix it.
Show answer
The plugin loader defines its own copy of Plugin only if it doesn't delegate to the parent, for example because it is child-first or because the parent can't see the host's copy. The two copies are different classes. Fix it by removing Plugin.class from the plugin directory so the parent's copy is used, or by making the loader delegate Plugin to the parent before looking in its own directory.