Class Loading
How the JVM finds and prepares classes — loading, linking (verification, preparation, resolution) and initialisation; the class loader hierarchy and parent delegation; custom loaders; and common ClassNotFound/NoClassDefFound problems.
The JVM doesn't load your whole program at start-up. Classes are loaded lazily, the first time they're actively used, by class loaders. Understanding this explains static initialisation order, plugin systems, app-server isolation, and some of the most confusing runtime errors.
The lifecycle of a class
Verification, preparation and resolution together are called linking.
1. Loading
A class loader finds the binary representation (a .class file in a JAR, a network resource, bytes generated at runtime), parses it, and creates a java.lang.Class object, storing its metadata in metaspace.
2. Linking
- Verification: the bytecode verifier checks the class is well-formed and type-safe — no stack overflows/underflows in a method, no jumping into the middle of an instruction, correct types for every operation, no access to private members of other classes. This is what lets the JVM run untrusted bytecode without crashing.
- Preparation: memory for static fields is allocated and set to default values (0, null, false) — not yet your initial values.
- Resolution: symbolic references in the constant pool (
com/example/Foo.bar:(I)V) are turned into direct references. HotSpot does this lazily, when an instruction first uses each reference.
3. Initialisation
The JVM runs the class's static initialiser — a synthetic method called <clinit> that contains all static field initialisers and static {} blocks in source order. Before that, the superclass is initialised.
Initialisation happens on first active use:
- creating an instance (
new), - calling a static method,
- reading or writing a static field (except compile-time constants, which are inlined),
- reflection (
Class.forName("X")), - initialising a subclass,
- being the main class.
class Config {
static { System.out.println("Config initialised"); }
static final int MAX = 10; // compile-time constant: inlined, no init
static final List<String> NAMES = List.of("a"); // not a constant: triggers init
}
System.out.println(Config.MAX); // prints 10 only — Config is NOT initialised
System.out.println(Config.NAMES); // "Config initialised", then [a]The JVM guarantees <clinit> runs exactly once, with a lock — other threads wait. That's why the holder idiom gives a thread-safe lazy singleton for free. It's also why a deadlock between two classes' static initialisers that reference each other is possible.
The class loader hierarchy
Parent delegation
When asked to load a class, a loader first delegates to its parent; only if the parent can't find it does it look itself.
- The application loader is asked for
java.lang.String. - It delegates to the platform loader, which delegates to bootstrap.
- Bootstrap finds
Stringinjava.baseand returns it. - For
com.example.App, the parents fail, so the application loader finds it on the classpath.
Why: security (your own java.lang.String on the classpath can never replace the real one) and consistency (core classes are loaded once and shared).
Class identity
A class at runtime is identified by its name plus its defining class loader. The same .class file loaded by two different loaders produces two different, incompatible classes:
java.lang.ClassCastException: class com.example.User cannot be cast to class com.example.User
(com.example.User is in unnamed module of loader 'app';
com.example.User is in unnamed module of loader org.springframework.boot.devtools.restart.classloader.RestartClassLoader)This classic error appears with hot-reload tools and app servers when objects cross loader boundaries.
Custom class loaders
Override findClass to load bytes from anywhere:
public class EncryptedClassLoader extends ClassLoader {
private final Path dir;
public EncryptedClassLoader(Path dir, ClassLoader parent) { super(parent); this.dir = dir; }
@Override
protected Class<?> findClass(String name) throws ClassNotFoundException {
try {
byte[] encrypted = Files.readAllBytes(dir.resolve(name.replace('.', '/') + ".class.enc"));
byte[] bytes = decrypt(encrypted);
return defineClass(name, bytes, 0, bytes.length);
} catch (IOException e) {
throw new ClassNotFoundException(name, e);
}
}
}Uses:
- Isolation: Tomcat gives each web app its own loader (and inverts delegation — child first — so apps can bundle their own library versions).
- Plugins: load plugin JARs with a
URLClassLoader, unload them by dropping all references to the loader. - Hot reload: Spring DevTools and JRebel restart a loader holding your code while keeping libraries loaded.
- Bytecode generation: frameworks (Hibernate, Mockito, Spring proxies) generate classes at runtime (ByteBuddy, ASM) and define them.
- Instrumentation: Java agents (
-javaagent) transform bytes at load time for APM and profiling.
Common errors
| Error | Meaning | Typical cause |
|---|---|---|
ClassNotFoundException (checked) | Dynamic lookup by name failed (Class.forName, loadClass) | Missing JAR, typo in a class name in config |
NoClassDefFoundError | A class present at compile time can't be found or initialised at runtime | Missing dependency at runtime, or a failed static initialiser |
NoSuchMethodError / NoSuchFieldError | The class was found but is a different version than compiled against | Dependency version conflicts ("JAR hell") — check mvn dependency:tree |
ClassCastException "X cannot be cast to X" | Same name, different loaders | Hot reload, app server, plugin boundaries |
UnsupportedClassVersionError | Compiled for a newer Java than the running JVM | Class file version 65 = Java 21 |
LinkageError: loader constraint violation | Two loaders disagree about a shared type | Duplicate libraries in parent and child loaders |
Debug with -verbose:class (or -Xlog:class+load) to see every class loaded and from where.
Class Data Sharing
Parsing and verifying thousands of classes slows start-up. CDS / AppCDS stores pre-processed class metadata in an archive mapped into memory at start-up (and shared between JVM processes). Java 24+ extends this with AOT cache (Project Leyden), which also stores linked classes and profiling data.
- Classes load lazily: loading → linking (verify, prepare, resolve) → initialisation.
- Static initialisers run once, thread-safely, on first active use; constants are inlined.
- Bootstrap → platform → application loaders with parent-first delegation.
- A runtime class is identified by name + loader: same name, different loader = different class.
- NoClassDefFoundError and NoSuchMethodError usually mean classpath or version problems.
QClassNotFoundException vs NoClassDefFoundError?medium
ClassNotFoundException is a checked exception thrown when code explicitly loads a class by name (Class.forName, ClassLoader.loadClass) and it can't be found. NoClassDefFoundError is an Error thrown when the JVM needs a class that existed at compile time but can't be loaded at runtime — because the JAR is missing or because its static initialiser previously failed.
QWhat is the parent delegation model and why does it exist?medium
A class loader first asks its parent to load a class and only searches itself if the parent fails, up to the bootstrap loader. It ensures core Java classes are always loaded by the trusted bootstrap loader (so they can't be spoofed) and that shared classes are loaded only once, giving a consistent type system.