Sub topic 13
Writing a Custom Class Loader
Prerequisites
This chapter assumes that you can compile and run Java programs, understand classes and methods, and use javac and java. You should also know that a .class file contains JVM bytecode.
A custom class loader is a class that turns class-file bytes into a Class<?> object. The JVM already provides class loaders for standard and application classes. You write a custom loader when classes must come from a special location, such as a plugin directory, database, network response, or encrypted store.
Preserve parent delegation
ClassLoader.loadClass normally follows parent delegation:
- Check whether the class was already loaded.
- Ask the parent loader to load it.
- Call
findClassif the parent cannot find it.
For this reason, override findClass instead of replacing loadClass. This keeps platform classes such as java.lang.Object under the normal loading rules.
A minimal custom loader
The following program loads MathOps.class from the current directory. The null parent means that this loader has no explicit parent. The bootstrap loader can still provide core Java classes.
First create and compile MathOps.java:
public class MathOps {
public static int add(int a, int b) {
return a + b;
}
}Then compile and run this loader:
import java.nio.file.Files;
import java.nio.file.Path;
public class LoadWithCustomLoader {
public static void main(String[] args) throws Exception {
byte[] bytes = Files.readAllBytes(Path.of("MathOps.class"));
ClassLoader loader = new BytesClassLoader(null, "MathOps", bytes);
Class<?> type = Class.forName("MathOps", true, loader);
System.out.println(type.getName());
System.out.println(type.getClassLoader());
}
private static final class BytesClassLoader extends ClassLoader {
private final String className;
private final byte[] classBytes;
private BytesClassLoader(
ClassLoader parent, String className, byte[] classBytes) {
super(parent);
this.className = className;
this.classBytes = classBytes;
}
@Override
protected Class<?> findClass(String name)
throws ClassNotFoundException {
if (!name.equals(className)) {
throw new ClassNotFoundException(name);
}
return defineClass(
name, classBytes, 0, classBytes.length);
}
}
}Run the example as follows:
javac MathOps.java LoadWithCustomLoader.java
java LoadWithCustomLoaderdefineClass checks the class-file bytes and creates a class associated with this defining loader. It does not automatically run static initialization. Class.forName receives true, so the JVM initializes the class after loading it.
Choosing a parent
Pass the application loader as the parent when the loaded class should use normal application dependencies:
ClassLoader parent = LoadWithCustomLoader.class.getClassLoader();Use a restricted parent, or carefully override loading rules, for plugin isolation. Such designs require care because a plugin may need selected shared interfaces from the parent while keeping its implementation classes separate.
Exercise
Why should a custom loader usually override findClass rather than loadClass?
Show answer
loadClass implements the normal parent-delegation process. Overriding findClass lets the parent have the first opportunity to load a class and defines bytes only when the parent cannot find it.