Understanding Class Loading

1. Understanding Class Loader Hierarchy

LoaderLoads
BootstrapCore JDK (java.base)
Platform (Java 9+)JDK platform modules
Application (System)Classpath / module-path
CustomPlugins, web apps, isolation

2. Using Bootstrap Class Loader

AspectDetail
ImplementationNative (C++)
ParentNone — represented as null
Loaded modulesjava.base and a few core

3. Using Platform Class Loader (Java 9+)

AspectDetail
ReplacesOld Extension class loader
AccessClassLoader.getPlatformClassLoader()
LoadsNon-base JDK platform modules

4. Using Application Class Loader

AspectDetail
AccessClassLoader.getSystemClassLoader()
ParentPlatform loader
LoadsApp classpath / module-path

5. Understanding Parent Delegation Model

StepAction
1Check own cache
2Delegate to parent
3Parent recurses to bootstrap
4If unresolved, this loader's findClass tries
Note: Web containers (Tomcat) deliberately invert delegation for WEB-INF/classes to isolate web apps.

6. Creating Custom Class Loaders

Example: Custom loader

public class MemoryClassLoader extends ClassLoader {
    private final Map<String, byte[]> classes;
    public MemoryClassLoader(ClassLoader parent, Map<String, byte[]> classes) {
        super(parent); this.classes = classes;
    }
    protected Class<?> findClass(String name) throws ClassNotFoundException {
        byte[] b = classes.get(name);
        if (b == null) throw new ClassNotFoundException(name);
        return defineClass(name, b, 0, b.length);
    }
}
OverrideUse
findClassStandard delegation
loadClassCustom delegation order

7. Loading Classes Dynamically (Class.forName)

FormBehavior
Class.forName("p.C")Initializes class
Class.forName(name, init, loader)Choose loader and init flag
loader.loadClass(name)Loads but does not initialize

8. Understanding Class Initialization

PhaseAction
LoadingBytes → Class object
LinkingVerify, prepare, resolve
InitializationRun static initializers and field assignments
TriggerFirst active use (new, static field/method, reflection forName(init=true))

9. Using Context Class Loader

APIUse
Thread.currentThread().getContextClassLoader()Get
setContextClassLoader(cl)Set
Use caseFrameworks discovering app classes from JDK code (ServiceLoader, JNDI)

10. Understanding Class Loader Isolation

AspectDetail
Class identityClass = (loader, fully qualified name)
Same class, different loadersConsidered DIFFERENT types — ClassCastException
UsePlugin sandboxing, hot reload

11. Resolving Class Loading Issues

ErrorCause / Fix
ClassNotFoundExceptionMissing on classpath; reflective lookup
NoClassDefFoundErrorClass loaded once but missing now (e.g., transitive dep)
LinkageErrorSame class loaded by two incompatible loaders
UnsupportedClassVersionErrorClass compiled for newer JVM
Diagnose-verbose:class, jcmd VM.class_hierarchy