Sub topic 10
Parent Delegation
The loading rule
Prerequisites: you should know how to compile and run Java programs, and you should understand classes, methods, and exceptions.
A class loader loads a class definition into the JVM. Java uses a parent delegation model to decide which loader should load a requested class.
When a loader receives a request for a class, it normally follows this order:
- Ask its parent loader to load the class.
- If the parent cannot find it, try to find the class itself.
- If neither loader finds it, throw
ClassNotFoundException.
This rule gives standard library classes a trusted, shared source. An application cannot normally replace java.lang.String with a class of its own.
`loadClass` and `findClass`
ClassLoader.loadClass implements the delegation process. A custom loader should usually override findClass, not loadClass. The inherited loadClass method asks the parent first and calls findClass only when necessary.
The defineClass method converts verified class-file bytes into a Class<?> object associated with that loader.
public class BytesClassLoader extends ClassLoader {
private final String className;
private final byte[] classBytes;
public BytesClassLoader(
ClassLoader parent, String className, byte[] classBytes) {
super(parent);
this.className = className;
this.classBytes = classBytes.clone();
}
@Override
protected Class<?> findClass(String name)
throws ClassNotFoundException {
if (!name.equals(className)) {
throw new ClassNotFoundException(name);
}
return defineClass(name, classBytes, 0, classBytes.length);
}
}The constructor receives a parent explicitly. If the parent cannot load the requested name, the inherited algorithm eventually calls this loader's findClass method.
Why delegation matters
Parent delegation prevents a child loader from silently replacing classes already visible to its parent. It also lets many parts of an application share one copy of a library.
A child-first loader reverses the priority: it searches its own locations before asking the parent. This can help plugins use different library versions, but it creates risks:
- The same class name can refer to different class definitions.
- A library may be incompatible with classes loaded by its parent.
- A type check or cast can fail even when class names look identical.
- Security-sensitive platform classes should not be loaded from application data.
A class is identified by both its fully qualified name and its defining class loader. Therefore, example.Plugin loaded by loader A is a different type from example.Plugin loaded by loader B.
Exercise
Exercise
Why should a custom class loader usually override findClass instead of loadClass?
Show answer
The inherited loadClass method preserves parent delegation. It asks the parent first and calls findClass only when the parent cannot load the class.