Class Loading in Java: The Loading Process, Loader Hierarchy and Namespaces
How the JVM finds and prepares classes: loading, linking and initialization, the bootstrap, platform and application loaders, parent-first delegation, plugin loaders, class loaders as namespaces, the context class loader, and tools for watching it all happen.
kvi5hnuCode Sprout team member11 min readOn this page
Part 9 is about security. It starts underneath the language, with the mechanism that brings code into the JVM. Java's safety guarantees (no pointer arithmetic, no unchecked casts, no out-of-bounds array access) hold only if every class file that enters the virtual machine is well formed and has not been tampered with, and if classes from different sources cannot impersonate each other. Class loaders and the bytecode verifier provide those guarantees. They are also everyday tools: plugin systems, application servers, test frameworks and the dynamic code of article 78 all rely on them. This article explains how classes are loaded. Article 81 writes a class loader and looks at verification.
From class file to usable class
The JVM loads classes lazily: only when they are first needed. For a program that starts with MyProgram, the JVM loads MyProgram.class, then whatever its execution actually touches. A class goes through three phases, defined in chapter 5 of the JVM specification:
- Loading finds the binary representation (from a JAR, a module image, the network, a byte array) and creates a
Classobject from it. A class loader does this. - Linking prepares the class for execution:
- verification checks that the bytecode is well formed and type-safe (article 81);
- preparation allocates static fields with default values;
- resolution turns symbolic references to other classes, fields and methods into direct ones, usually lazily, when an instruction first uses them.
- Initialization runs the static initializers and static field assignments, exactly once, the first time the class is actively used: a
new, a static method call, reading or writing a non-constant static field, a subclass being initialized, or reflection such asClass.forName(name).
The demo makes the difference visible:
- Reading
Lazy.CONSTANT, astatic final intinitialized with a compile-time constant, does not initializeLazy: the compiler copied the value 42 into the caller. Class.forName(name, false, loader)loads the class without initializing it.- Reading the non-constant
Lazy.countertriggers the static initializer. - A class literal such as
NeverUsed.classloads the class but does not initialize it.
To watch class loading, run a program with -verbose:class or -Xlog:class+load (add class+unload for unloading). Loading thousands of classes is a large part of startup time, which is why the JDK can cache loaded and linked classes ahead of time: class data sharing (CDS) and, since Java 24, the ahead-of-time cache (JEP 483; Java 25 simplified creating it with -XX:AOTCacheOutput, JEP 514).
The built-in class loaders
Every Java program runs with at least three class loaders:

| Loader | Loads | Java object |
|---|---|---|
| bootstrap | the core modules: java.base, java.logging, java.desktop, java.xml, ... | none; getClassLoader() returns null |
| platform | other Java SE and JDK modules: java.sql, java.compiler, ... | ClassLoader.getPlatformClassLoader() |
| application (system) | the class path, the module path, and JDK tool modules such as jdk.compiler | ClassLoader.getSystemClassLoader() |
Since Java 9, the platform classes come from the runtime image in lib/modules (the jrt: file system), not from rt.jar, and the old extension mechanism (jre/lib/ext) and endorsed-standards override are gone. The application loader is no longer a URLClassLoader, so old tricks that cast it to add JARs at run time fail. Which loader a module belongs to is an implementation decision of the JDK and has changed between releases; code should not depend on it.
Parent-first delegation
Class loaders form a tree. Every loader except the bootstrap loader has a parent, and the standard loadClass method follows a fixed algorithm:
- If this loader already loaded the class, return it.
- Ask the parent to load it.
- Only if the parent fails, call
findClassto look for it locally.
So when the application loader is asked for java.lang.String, the request goes up to the bootstrap loader, which finds it. This has two important consequences. Core classes always come from the platform: a JAR on the class path cannot replace java.lang.String. (The module system also forbids two modules from containing the same package, and the java.* packages can only be defined by the platform.) And classes loaded by a child can always see their parents' classes, but not the reverse.
Plugin loaders
To load optional code at run time, create a loader for it:
var pluginLoader = new URLClassLoader("plugins", new URL[] { jarPath.toUri().toURL() },
ClassLoader.getSystemClassLoader());
Class<?> cls = pluginLoader.loadClass("com.example.MyPlugin");
var plugin = (Supplier<String>) cls.getConstructor().newInstance();
The plugin's classes can use everything the application can, including the interface it implements, because the application loader is the parent. The application code works with the plugin only through that interface. For modular plugins, ModuleLayer and ModuleFinder create a new layer of modules with its own loaders, and ServiceLoader.load(layer, Service.class) finds the implementations.
Class loaders as namespaces
A class is identified by its fully qualified name and its defining class loader. Two loaders can therefore both load a class called Plugin, even from the same JAR, and the JVM treats them as two distinct, unrelated classes. The demo compiles two versions of Plugin and loads them with three loaders:
v1andv1-againload the same class file, but produce differentClassobjects;- an instance from
v1cannot be cast to thePluginclass ofv2(ClassCastException, even though the names match); - all of them implement
Supplier<String>, which comes from the bootstrap loader and is shared, so the host can use any of them.
Application servers use exactly this to run several applications, each with its own versions of libraries, in one JVM. It is also the reason for the most confusing error message in Java, ClassCastException: class X cannot be cast to class X: the same class loaded twice by different loaders.
A loader asked twice for the same name returns the same class. And when no references to a loader, its classes and their instances remain, the garbage collector can unload them all, which is how servers redeploy applications.
The context class loader
Delegation goes upward, which creates a problem for libraries. Suppose a framework class, loaded by the application loader, calls Class.forName(className) to instantiate a class named in a configuration file. Class.forName uses the loader of the calling class, so it cannot see classes that a plugin loader defined below it. This is sometimes called class loader inversion.
The conventional solution is the thread's context class loader:
Thread t = Thread.currentThread();
t.setContextClassLoader(pluginLoader);
...
ClassLoader loader = Thread.currentThread().getContextClassLoader();
Class<?> cls = Class.forName(className, true, loader);
A new thread inherits the context loader of the thread that created it; the main thread's is the application loader. Frameworks such as JNDI, JAXP and ServiceLoader.load(Class) (without a loader argument) use the context class loader. When you write a method that loads classes by name, let the caller pass a class loader, and fall back to the context class loader rather than your own class's loader.
Resources
getResource and getResourceAsStream follow the same delegation as classes, so resources in the platform win over resources on the class path. Class.getResource("name") resolves the name relative to the class's package; ClassLoader.getResource expects a full path without a leading slash. For classes in named modules, resources in the module's own packages are encapsulated unless the package is opened.
The program
The demo prints the defining loader of classes from several modules, follows the parent chain, makes the phases of class initialization visible, compiles two versions of a plugin and loads them through separate URLClassLoaders to show class identity, and demonstrates the context class loader.
import java.io.*;
import java.net.*;
import java.nio.file.*;
import java.util.*;
import javax.tools.*;
public class Solution {
static class Lazy {
static { System.out.println(" [Lazy initialized]"); }
static final int CONSTANT = 42; // compile-time constant: inlined, no initialization
static int counter = 7; // not a constant: reading it initializes Lazy
}
static class NeverUsed {
static { System.out.println(" [NeverUsed initialized - should not appear]"); }
}
public static void main(String[] args) throws Exception {
System.out.println("== Who loaded what ==");
for (Class<?> c : List.of(String.class, java.util.logging.Logger.class, java.sql.Connection.class,
javax.tools.ToolProvider.class, com.sun.source.tree.Tree.class, Solution.class)) {
System.out.printf("%-30s module %-14s loader %s%n", c.getName(), c.getModule().getName(),
name(c.getClassLoader()));
}
ClassLoader app = ClassLoader.getSystemClassLoader();
System.out.println("chain from the application loader: " + name(app) + " -> "
+ name(app.getParent()) + " -> " + name(app.getParent().getParent()));
System.out.println("platform loader == app.getParent(): " + (ClassLoader.getPlatformClassLoader() == app.getParent()));
System.out.println("app loader is a URLClassLoader: " + (app instanceof URLClassLoader));
System.out.println("\n== Loading, linking, initialization ==");
System.out.println("reading Lazy.CONSTANT = " + Lazy.CONSTANT);
Class<?> loaded = Class.forName("Solution$Lazy", false, Solution.class.getClassLoader());
System.out.println("forName(..., initialize=false) returned " + loaded.getSimpleName());
System.out.println("reading Lazy.counter:");
System.out.println(" value " + Lazy.counter);
System.out.println("NeverUsed.class literal: " + NeverUsed.class.getSimpleName()
+ " (a class literal does not initialize)");
System.out.println("\n== Class loaders as namespaces ==");
Path dir = Files.createTempDirectory("loaders");
try {
Path v1 = compile(dir.resolve("v1"), "public class Plugin implements java.util.function.Supplier<String> "
+ "{ public String get() { return \"plugin version 1\"; } }");
Path v2 = compile(dir.resolve("v2"), "public class Plugin implements java.util.function.Supplier<String> "
+ "{ public String get() { return \"plugin version 2\"; } }");
try (var l1 = new URLClassLoader("v1", new URL[] {v1.toUri().toURL()}, app);
var l1b = new URLClassLoader("v1-again", new URL[] {v1.toUri().toURL()}, app);
var l2 = new URLClassLoader("v2", new URL[] {v2.toUri().toURL()}, app)) {
Class<?> a = l1.loadClass("Plugin");
Class<?> b = l1b.loadClass("Plugin");
Class<?> c = l2.loadClass("Plugin");
System.out.println("same name: " + a.getName().equals(c.getName()) + ", same class v1/v1-again: " + (a == b)
+ ", same class v1/v2: " + (a == c));
System.out.println("loading twice from one loader gives the same class: " + (a == l1.loadClass("Plugin")));
for (Class<?> k : List.of(a, b, c)) {
@SuppressWarnings("unchecked")
var s = (java.util.function.Supplier<String>) k.getConstructor().newInstance();
System.out.println(" " + name(k.getClassLoader()) + ": " + s.get());
}
Object fromV1 = a.getConstructor().newInstance();
try {
c.cast(fromV1);
} catch (ClassCastException e) {
System.out.println("casting a v1 Plugin to the v2 Plugin class: ClassCastException");
}
System.out.println("the shared interface works across both: "
+ (fromV1 instanceof java.util.function.Supplier<?>));
System.out.println("app loader cannot see Plugin: " + canLoad(app, "Plugin"));
}
System.out.println("\n== The context class loader ==");
Path v3 = compile(dir.resolve("v3"), "public class Helper { }");
try (var pluginLoader = new URLClassLoader("plugin", new URL[] {v3.toUri().toURL()}, app)) {
System.out.println("forName with the caller's loader finds Helper: " + canForName("Helper", null));
Thread t = Thread.currentThread();
ClassLoader saved = t.getContextClassLoader();
t.setContextClassLoader(pluginLoader);
try {
System.out.println("forName with the context loader finds Helper: "
+ canForName("Helper", t.getContextClassLoader()));
Thread child = new Thread(() -> System.out.println("new thread inherits context loader: "
+ name(Thread.currentThread().getContextClassLoader())));
child.start();
child.join();
} finally {
t.setContextClassLoader(saved);
}
}
} finally {
try (var files = Files.walk(dir)) {
files.sorted(Comparator.reverseOrder()).forEach(f -> f.toFile().delete());
}
}
System.out.println("\n== Resources go through the same delegation ==");
System.out.println("String.class resource: " + String.class.getResource("String.class").getProtocol());
System.out.println("app loader finds java/lang/Object.class: "
+ (app.getResource("java/lang/Object.class") != null));
}
static String name(ClassLoader l) {
return l == null ? "bootstrap (null)" : l.getName();
}
static boolean canLoad(ClassLoader l, String n) {
try { l.loadClass(n); return true; } catch (ClassNotFoundException e) { return false; }
}
static boolean canForName(String n, ClassLoader l) {
try {
if (l == null) Class.forName(n); else Class.forName(n, true, l);
return true;
} catch (ClassNotFoundException e) {
return false;
}
}
static Path compile(Path out, String source) throws IOException {
Path src = out.resolve("src");
Files.createDirectories(src);
String cls = source.replaceAll("(?s).*?class (\\w+).*", "$1");
Path file = src.resolve(cls + ".java");
Files.writeString(file, source);
Path classes = out.resolve("classes");
Files.createDirectories(classes);
int rc = ToolProvider.getSystemJavaCompiler().run(null, null, null, "-d", classes.toString(), file.toString());
if (rc != 0) throw new IllegalStateException("compile failed");
return classes;
}
}
== Who loaded what ==
java.lang.String module java.base loader bootstrap (null)
java.util.logging.Logger module java.logging loader bootstrap (null)
java.sql.Connection module java.sql loader platform
javax.tools.ToolProvider module java.compiler loader platform
com.sun.source.tree.Tree module jdk.compiler loader app
Solution module null loader app
chain from the application loader: app -> platform -> bootstrap (null)
platform loader == app.getParent(): true
app loader is a URLClassLoader: false
== Loading, linking, initialization ==
reading Lazy.CONSTANT = 42
forName(..., initialize=false) returned Lazy
reading Lazy.counter:
[Lazy initialized]
value 7
NeverUsed.class literal: NeverUsed (a class literal does not initialize)
== Class loaders as namespaces ==
same name: true, same class v1/v1-again: false, same class v1/v2: false
loading twice from one loader gives the same class: true
v1: plugin version 1
v1-again: plugin version 1
v2: plugin version 2
casting a v1 Plugin to the v2 Plugin class: ClassCastException
the shared interface works across both: true
app loader cannot see Plugin: false
== The context class loader ==
forName with the caller's loader finds Helper: false
forName with the context loader finds Helper: true
new thread inherits context loader: plugin
== Resources go through the same delegation ==
String.class resource: jrt
app loader finds java/lang/Object.class: true
Common questions
What's the difference between ClassNotFoundException and NoClassDefFoundError?
ClassNotFoundException is thrown when code explicitly asks for a class by name (Class.forName, loadClass) and it can't be found. NoClassDefFoundError means a class was present at compile time but is missing (or failed to initialize earlier) when the JVM needs it during execution, usually a class-path problem in deployment.
How do I add a JAR to the class path at run time?
You can't add it to the application loader in current Java (it isn't a URLClassLoader). Create a URLClassLoader for the JAR with the application loader as parent and load classes through it, or use ModuleLayer for modules. The -javaagent mechanism's Instrumentation.appendToSystemClassLoaderSearch is a special-purpose exception.
What does "class X cannot be cast to class X" mean?
Two class loaders each loaded their own X. The message usually names both loaders. Make sure the shared type comes from a common parent loader, and that plugins don't bundle their own copy of the interfaces they share with the host.
Does Class.forName initialize the class?
Class.forName(name) does. Class.forName(name, false, loader) and loader.loadClass(name) only load it; initialization happens at first active use. That matters when static initializers have side effects, such as JDBC drivers registering themselves.
How can I see why a class was loaded from the wrong JAR?
Run with -verbose:class (or -Xlog:class+load), which prints each class with its source location. In code, X.class.getProtectionDomain().getCodeSource().getLocation() tells you where a class came from.
API reference
| Method | Purpose |
|---|---|
Class.getClassLoader() | defining loader (null for bootstrap) |
ClassLoader.getSystemClassLoader(), getPlatformClassLoader() | built-in loaders |
ClassLoader.getParent(), getName() | hierarchy and names |
ClassLoader.loadClass(name) | load with delegation, without initializing |
Class.forName(name), Class.forName(name, initialize, loader) | load (and optionally initialize) |
new URLClassLoader(name, URL[], parent) | load classes from JARs and directories |
Thread.getContextClassLoader(), setContextClassLoader | per-thread loader for frameworks |
ClassLoader.getResource, getResources, getResourceAsStream | resources through delegation |
ModuleLayer, ModuleFinder, ServiceLoader.load(layer, type) | modular plugin layers |
-verbose:class, -Xlog:class+load, -Xlog:class+unload | trace loading |
Summary
- Classes are loaded lazily, then linked (verified, prepared, resolved) and initialized on first active use; compile-time constants and class literals do not trigger initialization.
- The bootstrap loader (
null), platform loader and application loader form a hierarchy; since Java 9 the application loader is not aURLClassLoader. - Loaders delegate to their parent first, so platform classes cannot be replaced and children see their parents' classes.
- Use a child loader, such as a
URLClassLoader, for plugins, and talk to plugins through interfaces loaded by a common parent. - A class's identity is its name plus its defining loader; the same class file loaded twice gives two incompatible classes.
- Frameworks loading classes by name should accept a loader or use the context class loader; restore the context loader after changing it.
Practice Questions
1. Which of these initializes class C: reading C.MAX (static final int MAX = 10), C.class.getName(), Class.forName("C"), new C[5], C.create()?
Only Class.forName("C") (which initializes by default) and the static method call C.create(). C.MAX is a compile-time constant and is inlined by the compiler. A class literal and getName() only need the loaded Class object. Creating an array of C loads the class and creates an array class, but does not initialize C.
2. A plugin JAR contains its own copy of java/lang/String.class. Can it replace the platform's String? Explain.
No. The plugin loader delegates the request for java.lang.String to its parent, which eventually reaches the bootstrap loader. The bootstrap loader finds the platform's String, so the plugin's copy is never loaded. In addition, only the platform may define classes in java.* packages, so defining it directly with defineClass throws a SecurityException.
3. What does "ClassCastException: class com.acme.Config cannot be cast to class com.acme.Config" mean?
Two different class loaders each loaded a class named com.acme.Config, often because the JAR is both in the application's class path and in a plugin's or web application's own library directory. The object was created from one Class, and the cast uses the other. Make sure shared types are loaded only once, by a common parent loader, typically by removing the duplicate JAR from the child.
4. A JSON library uses Class.forName(typeName) to instantiate classes named in documents. It fails for classes that belong to a plugin. Why, and what is the usual fix?
Class.forName(name) uses the defining loader of the library class, which sits above the plugin loader and cannot see the plugin's classes. The library should accept a ClassLoader from the caller, or use Thread.currentThread().getContextClassLoader(), and the plugin host sets the context loader to the plugin's loader while the plugin runs, restoring it afterwards.
5. A server redeploys a web application many times and metaspace keeps growing. How is that related to class loaders?
Each deployment gets a new class loader, and its classes can only be unloaded when nothing references the loader, its classes or their instances. A single leftover reference, such as a thread whose context class loader is the old loader, a JDBC driver registered in DriverManager, a ThreadLocal value, or a static cache in a shared library, keeps the whole old application and its classes alive. Find such references with a heap dump and remove them when the application is stopped.
Previous: The Java Scripting API: Script Engines, Bindings and Invocable
Next: Writing a Class Loader and Bytecode Verification in Java
Related reading
- Resource Bundles in Java: Locating Bundles, Property Files and Bundle Classes
- Java Regular Expressions: Syntax, Character Classes and Quantifiers
- The Java Serialization File Format: Handles, Class Descriptors and Fingerprints
- Java Reflection and Generics: Class<T>, Type Tokens and the Type Interface
- Java Generics Inheritance Rules and Wildcards: extends, super and ?

More in Core Java II
FFM Upcalls, Variadic Functions and errno
Advanced FFM calls: passing Java code to C as function pointers with upcall stubs, binding objects and lambdas, calling variadic functions such as printf, capturing errno and GetLastError, and a C library that calls back into Java. The final article of the course.
Calling Foreign Functions: Linker, Symbol Lookup, Downcalls and jextract
Calling C functions from pure Java with the FFM API: the native linker, default, library and loader symbol lookups, function descriptors, downcall handles, invokeExact, pointers and NULL, struct results, critical calls, enabling native access, and generating bindings with jextract.
FFM Memory Layouts: Structs, Unions, Sequences and Var Handles
Describing C data with FFM memory layouts: value layouts and C types, struct and union layouts, alignment and padding, sequences, layout paths, var handles with base offsets, offset and slice handles, pointers with target layouts, and atomic access modes.
Foreign Function and Memory API: Arenas and Memory Segments
Getting started with the FFM API (final since Java 22): a first foreign call, confined, shared, automatic and global arenas, native and heap memory segments, reading and writing values, C strings and arrays, alignment and byte order, slices, copies, allocators, and memory-mapped files.
Discussion
Sign in to ask a question or share what you learned.