Skip to main content

Java ClassLoaders Explained: Delegation, Custom Loaders, ClassNotFoundException vs NoClassDefFoundError

What a Java class loader really is, why a class is its name plus its loader, how parent delegation works (traced line by line on JDK 25), how to write a child-first plugin loader, why “X cannot be cast to X” happens, and how to tell ClassNotFoundException from NoClassDefFoundError, including the ‘Could not initialize class’ trap. Every output comes from a real run in the companion repo.

You compile a program, it runs on your laptop, and in production it dies with java.lang.NoClassDefFoundError on a class you can see sitting in the jar. Or you build a plugin system, load version 2 of a plugin, and Java insists that com.acme.GreeterPlugin cannot be cast to com.acme.GreeterPlugin. Both problems have the same root: you have never been told who loads a class, and that “who” is part of the class’s identity. This post starts from zero. Every claim below comes from a program that was compiled and run on JDK 25, and every code block and output block links to the file in the companion repository it came from. The long-tail material lives in the collapsible sections, so you can read straight through or open only what you need.
Versions tested. JDK 25.0.5.1 (Temurin; JDK 25 went GA on 16 September 2025 and is an LTS release), Maven 3.9.11, JUnit Jupiter 5.11.0. The companion code is the classloaders module of java-core-examples; run scripts/run-all.sh to regenerate every output shown here. The JDK 25 ClassLoader Javadoc is the primary reference.

A class is its name plus the loader that defined it

A class loader is an object whose job is to turn the bytes of a .class file into a Class in memory. Every class remembers which loader defined it. Two classes with the same fully qualified name, defined by two different loaders, are two unrelated classes as far as the JVM is concerned: different Class objects, different static fields, and no cast between them.
app loader Plugin (the interface), defined once loader ‘plugin-v1’ com.acme.GreeterPlugin (v1) loader ‘plugin-v2’ com.acme.GreeterPlugin (v2) Same name, two loaders, two different classes. Both implement the one shared Plugin. That shared interface is what lets the host talk to both.
The picture is the whole reason this topic matters: the diagram’s two GreeterPlugin boxes are the “cannot cast X to X” error waiting to happen, and the single shared Plugin box above them is the fix. Keep both in mind; the rest of the page cashes them in.

Three built-in loaders, one parent chain

Every JVM starts with three loaders. The bootstrap loader is built into the VM and is represented in Java code as null. The platform loader and the application (system) loader are ordinary Java objects named "platform" and "app". Each loader has a parent; the application loader’s parent is the platform loader, and the platform loader’s parent is the bootstrap loader. HierarchyDemo asks the JVM who defined a handful of classes (HierarchyDemo.java):
java.lang.String             -> null (the bootstrap loader)
java.util.ArrayList          -> null (the bootstrap loader)
java.sql.Driver              -> 'platform' (jdk.internal.loader.ClassLoaders$PlatformClassLoader)
javax.tools.JavaCompiler     -> 'platform' (jdk.internal.loader.ClassLoaders$PlatformClassLoader)
HierarchyDemo (this class)   -> 'app' (jdk.internal.loader.ClassLoaders$AppClassLoader)
int[]                        -> null (the bootstrap loader)
HierarchyDemo[]              -> 'app' (jdk.internal.loader.ClassLoaders$AppClassLoader)
That is a trimmed copy of output/01-hierarchy.txt. Two things to read off it. First, getClassLoader() returning null does not mean “no loader”; it means the bootstrap loader. Second, an array class takes the loader of its element type, which is why int[] is null and HierarchyDemo[] is 'app'.
‘app’ (system) loader class path, plus 19 JDK modules such as jdk.compiler ‘platform’ loader 21 JDK modules such as java.sql and java.compiler bootstrap loader (null in Java code) 21 JDK modules including java.base, java.desktop parent parent
The module counts in the diagram come from the same run, and they deserve a second look. The surprise is that java.desktop and java.sql are not owned by the same loader: on this build the bootstrap loader owns 21 modules and the platform loader another 21, so “all JDK classes come from the bootstrap loader” is not true.
app         19 modules, e.g. [jdk.attach, jdk.compiler, jdk.editpad, jdk.internal.ed]
bootstrap   21 modules, e.g. [java.base, java.datatransfer, java.desktop, java.instrument]
platform    21 modules, e.g. [java.compiler, java.net.http, java.scripting, java.security.jgss]
Those three lines are also from output/01-hierarchy.txt. The split is a property of the JDK build, so treat the exact numbers as “what this Temurin 25.0.5.1 reported”, not as a specification.
Going further: named modules, unnamed modules, and where your class actually lives A class from your class path is in the unnamed module of the loader that defined it; HierarchyDemo.class.getModule().isNamed() is false in the same transcript, while String.class.getModule() prints module java.base. The loader decides which modules it defines (that is what the 19/21/21 split above is), and the Javadoc notes that the platform loader can delegate to the application loader when modules are upgraded or overridden. If you meet --patch-module or --upgrade-module-path one day, this is where the exceptions to the neat three-box picture come from. Everything in this accordion is the intermediate layer; nothing later in the post depends on it.

Parent delegation: ask your parent first

When you ask a loader for a class it does not simply look in its own directory. By default it asks its parent first, and only searches itself if the parent says “not mine”. The Javadoc describes the default loadClass as: check whether this loader already loaded it, then ask the parent, then call findClass. The practical consequence is that nobody can slip a fake java.lang.String in front of the real one: the request always reaches the bootstrap loader first. To make the order visible I wrote the smallest useful loader, DirLoader, which reads .class files from one directory. It overrides findClass, not loadClass, so the delegation logic stays intact. The only reason it touches loadClass is to print the request before calling super (DirLoader.java; the logging lines are left out here):
@Override
protected Class<?> findClass(String name) throws ClassNotFoundException {
    Path file = dir.resolve(name.replace('.', '/') + ".class");
    if (!Files.exists(file)) {
        throw new ClassNotFoundException(name);
    }
    byte[] bytes = Files.readAllBytes(file);
    return defineClass(name, bytes, 0, bytes.length);
}
DelegationDemo chains two of them. shared holds Lib; child holds UsesLib, whose run() calls new Lib(). Here is what happens when we ask child for UsesLib and then run it (DelegationDemo.java, plugin sources UsesLib.java and Lib.java):
== child.loadClass("com.acme.UsesLib") ==
  [child] loadClass(com.acme.UsesLib)
  [shared] loadClass(com.acme.UsesLib)
  [shared]   findClass(com.acme.UsesLib) -> not in my directory
  [child]   findClass(com.acme.UsesLib) -> defineClass
  defined by: 'child' (com.ankurm.classloaders.DirLoader)

== Running it: UsesLib needs Lib, which triggers a second load ==
  [child] loadClass(com.acme.shared.Lib)
  [shared] loadClass(com.acme.shared.Lib)
  [shared]   findClass(com.acme.shared.Lib) -> defineClass
  result: UsesLib called Lib
The captured file is output/02-delegation.txt. Read the first block top to bottom: child was asked, child asked shared, shared looked in its directory and failed, and only then did child call defineClass. In the second block the order flips for Lib, because the parent does have it and the child never gets to define it.
child loader asked for a class parent loader has it? define it, stop grandparent … up to the bootstrap loader 1 ask 2 ask 3 “not mine” bubbles back down only now: child.findClass() The child defines a class only after every ancestor has declined.
That last sentence of the diagram is the rule to remember, and it has a consequence you will meet again in the plugin section: if the parent already has a class, the child’s copy is never even looked at.
Override findClass, not loadClass. The Javadoc says subclasses should override findClass. Overriding loadClass is how you break delegation by accident. The one legitimate reason is a deliberate child-first loader, which is what we build further down, and it has to be written with care.
Going further: the three steps inside loadClass, locks, and the java.* rule Per the Javadoc, the default loadClass(name, resolve) does three things in order: findLoadedClass (the loader’s own cache), the parent’s loadClass (or the built-in bootstrap path when the parent is null), then findClass. That first step is why a loader never defines the same name twice. It also explains something you will see later: a dependency that is already loaded survives its .class file being deleted, because the loader answers from its cache.

loadClass holds a lock while it works. A plain loader locks on itself; a loader that registers as parallel capable (call ClassLoader.registerAsParallelCapable() in a static initialiser, as PluginLoader.java does) gets one lock per class name through getClassLoadingLock(name). The Javadoc warns that loaders with non-hierarchical delegation should be parallel capable or class loading can deadlock.

Finally, defineClass refuses names that start with java.. The test javaPackageCannotBeDefinedByACustomLoader asserts the exact SecurityException text (Prohibited package name: java.lang), so you can see that no custom loader can impersonate the JDK.

Loading a class is not the same as running its static code

Beginners often assume that once a class is loaded its static { ... } block has run. It has not. Loading finds and defines the class; initialisation runs the static block, and the JVM delays that until the first real use. ClassLoader.loadClass and Class.forName(name, false, loader) load without initialising; Class.forName(name) and Class.forName(name, true, loader) initialise. The distinction matters because the scariest error in this post is an initialisation failure disguised as a missing class.
== loadClass: loads and links, does NOT initialise ==
  loaded com.acme.Noisy, nothing printed above this line

== First real use triggers initialisation (static method call) ==
  >> Noisy static initialiser ran

== Class.forName(name, true, loader): loads and initialises immediately ==
  >> Noisy static initialiser ran
  done
The program is ForNameDemo.java, the class with the noisy static block is Noisy.java, and the transcript (trimmed here, the middle section is identical to the first) is output/03-forname-vs-loadclass.txt.
  • JDBC’s old Class.forName("com.mysql.jdbc.Driver") idiom existed precisely to trigger that static block, which registered the driver. Modern drivers register through ServiceLoader instead; see the context-loader section below.

ClassNotFoundException vs NoClassDefFoundError

These two have different parents in the type hierarchy and different meanings. ClassNotFoundException is a checked exception: your code asked a loader for a class by its string name (Class.forName, loadClass) and nobody had it. NoClassDefFoundError is an error raised by the JVM itself: some class that was present when your code was compiled could not be found, or could not be initialised, when the JVM needed it at run time.
ClassNotFoundExceptionNoClassDefFoundError
KindChecked exceptionError (a LinkageError)
Who raises itA loader, when you ask by string nameThe JVM, while linking or running your compiled code
Typical causeTypo, missing jar, wrong loaderA compile-time dependency missing at run time, or a failed static initialiser
What to check firstClass path and the loader you askedThe cause chain, and earlier log lines
The three scenarios below are produced on purpose by ErrorsDemo.java. For scenario 2, Holder compiles against Dep, and the demo deletes Dep.class afterwards (sources: Holder.java, Dep.java). Writing this demo cost one wrong first attempt: the first version printed no error at all, because Dep had already been loaded and the loader kept serving it from its cache. The fix was to show both cases.
== 1. ClassNotFoundException: asking by name for a class nobody has ==
  java.lang.ClassNotFoundException: com.acme.DoesNotExist
  checked exception? true

== 2. NoClassDefFoundError: compiled against Dep, Dep.class missing at run time ==
  with Dep.class present:                 Dep is here
  ...Dep.class deleted from disk...
  same loader, Dep already loaded:        Dep is here   (the loader cached it)
  fresh loader, Dep never loaded:
    java.lang.NoClassDefFoundError: com/acme/missing/Dep
    caused by: java.lang.ClassNotFoundException: com.acme.missing.Dep
    is an Error, not an Exception: true
Output file: output/04-errors.txt. Notice two details. The NoClassDefFoundError message uses slashes (com/acme/missing/Dep), the JVM’s internal name format, while its cause is a plain ClassNotFoundException with dots. So the error is the JVM’s wrapper, and the exception is what actually happened underneath. The second detail is the cache: a class a loader has already defined stays usable even after its file is gone. Scenario 3 is the one that wastes afternoons. The class file is present and valid. Its static initialiser throws on first use (Broken.java):
public class Broken implements Plugin {
    static final int LIMIT = Integer.parseInt("not-a-number");

    @Override
    public String run() {
        return "never reached " + LIMIT;
    }
}
Using it twice gives two different failures:
== 3. NoClassDefFoundError: "Could not initialize class" (the class file is fine) ==
  attempt 1: java.lang.ExceptionInInitializerError, cause java.lang.NumberFormatException: For input string: "not-a-number"
  attempt 2: java.lang.NoClassDefFoundError: Could not initialize class com.acme.initfail.Broken
             cause: java.lang.ExceptionInInitializerError: Exception java.lang.NumberFormatException: For input string: "not-a-number" [in thread "main"]
Same file, output/04-errors.txt. The first use throws ExceptionInInitializerError with the real cause. The JVM then marks the class as failed, and every later use throws NoClassDefFoundError: Could not initialize class. In production the first error scrolls past in one request and the second one repeats forever, so the log you stare at has the misleading one. On JDK 25 the later error carries the original as its cause, as the transcript shows; the contract test failedStaticInitialiserFirstThrowsEiiThenNoClassDefFoundErrorWithCause pins that. Older JDKs omitted the cause (the OpenJDK bug JDK-8301173 lists 7u60 through 17 as affected and was backported to 8u361), so on an older runtime you may have to find the first error in the logs yourself.
The fingerprint. NoClassDefFoundError: Could not initialize class X means X was found. Do not touch the class path. Search the log, from the beginning of the process, for the first ExceptionInInitializerError mentioning X.
Going further: a diagnosis checklist for “it ran on my machine” Work through these in order; the first four are what we reproduced above, the rest are common causes that this module does not reproduce, so verify them in your own project.

1. Read the cause of the error. If it is a ClassNotFoundException, the class file is missing from the run-time class path. If it is an ExceptionInInitializerError, the file is fine and a static block or static field initialiser failed.
2. Ask the JVM where it found things: run with -Xlog:class+load and look at the source: column (see the logging section below).
3. If the class is missing only in one environment, compare the class path or the packaged jar of that environment against the build that compiled it.
4. If the class is present but still “not found”, ask which loader is looking. A class visible to the application loader is invisible to a sibling plugin loader, and a class that only a child loader can see is invisible to code defined by a parent (this is the reason the context loader exists, below).
5. Not reproduced here: dependency scopes that put a library at compile time but not at run time, and duplicate jars with different versions of the same class. Both produce the same two errors.

Writing a plugin loader, and why the cast fails

Here is the situation that makes people write their own loader. Your host application defines a Plugin interface, and third parties drop in jars with their own classes. You want each plugin isolated and replaceable. So you create one loader per plugin, give it the plugin’s directory, and set its parent to the application loader so everything on the host side (the Plugin interface, the JDK) is shared. The contract is one tiny interface (Plugin.java):
public interface Plugin {
    String run();
}
The two plugin versions are the same class name with different bodies: v1/GreeterPlugin.java and v2/GreeterPlugin.java. PluginDemo compiles both at run time and loads each in its own named loader (PluginDemo.java):
== Class identity = name + defining loader ==
  same name:            true
  same Class object:    false
  c1 loader:            'plugin-v1' (com.ankurm.classloaders.PluginLoader)
  c2 loader:            'plugin-v2' (com.ankurm.classloaders.PluginLoader)
  both usable as Plugin (the interface is shared via the parent):
    p1.run() = Hello from GreeterPlugin v1
    p2.run() = Hello from GreeterPlugin v2
  c2.cast(p1): Cannot cast com.acme.GreeterPlugin to com.acme.GreeterPlugin
This is the first section of output/05-plugins.txt, and it is diagram one proven in running code. The last line is the famous “X cannot be cast to X”: the names are equal, the classes are not. Now the way it goes wrong in real systems. If your plugin loader is child-first and you let it apply that to everything, including the host’s API package, the plugin gets its own private copy of Plugin. The plugin class then implements its Plugin, while your host code is compiled against another one:
app loader (the host) Plugin (copy A) loader ‘plugin-bad’ GreeterPlugin Plugin (copy B) (Plugin) obj asks for copy A. The object implements copy B. ClassCastException. Fix: never load the shared API child-first; let the parent supply the one copy.
The dashed red line is the failed cast. The captured message is long but precise, and it names both loaders, which is exactly why naming your loaders (the ClassLoader(String name, ClassLoader parent) constructor, since JDK 9) is worth the one extra argument:
  ClassCastException: class com.acme.GreeterPlugin cannot be cast to class com.ankurm.classloaders.api.Plugin (com.acme.GreeterPlugin is in unnamed module of loader 'plugin-bad' @<hash>; com.ankurm.classloaders.api.Plugin is in unnamed module of loader 'app')
From the same output/05-plugins.txt (the transcript replaces the object hash with @<hash> so reruns diff cleanly). Read it as “the class is in loader ‘plugin-bad’ and the interface I cast to is in loader ‘app'”: the names match, the loaders do not. The loader that produced the bug is PluginLoader.java, whose core is a predicate deciding which names are searched in the plugin’s own URLs before the parent:
synchronized (getClassLoadingLock(name)) {
    Class<?> c = findLoadedClass(name);
    if (c == null && !name.startsWith("java.") && selfFirst.test(name)) {
        try {
            c = findClass(name); // look in my own URLs first
        } catch (ClassNotFoundException notHere) {
            // fall through to the parent
        }
    }
    if (c == null) {
        return super.loadClass(name, resolve); // parent-first for everything else
    }
    if (resolve) resolveClass(c);
    return c;
}
The good configuration passes n -> n.startsWith("com.acme."), so only the plugin’s own package is child-first. The bad configuration in the demo adds the host’s API package too, and the cast breaks.
Going further: choosing what is shared and what is child-first A plugin loader is a sorting decision about every class name: shared (parent supplies it, so host and plugin agree on one copy) or private (plugin supplies it, so the plugin can use its own version of a library). The API the host and plugin talk across must be shared. Everything the plugin merely uses internally can be private. java.* must never be child-first; the loader here refuses it and the JVM would refuse a definition anyway.

The cost of a private library is that its types cannot cross the boundary. If a plugin returns a com.google.common.collect.ImmutableList from its own private Guava, the host cannot use it as its ImmutableList; the same identity rule bites. The safe boundary type is something from the JDK or from your shared API.

The loader also registers itself parallel capable in a static initialiser. If you copy it, keep the synchronized (getClassLoadingLock(name)) wrapper; without it two threads could race to define the same class (a general rule from the Javadoc’s locking notes, not something this module reproduces).

Hot reload, and the day your loader refuses to die

You cannot unload a single class in Java. A class goes away only when its loader becomes unreachable and the garbage collector runs. That is why hot reload creates a new loader per version and drops the old one. In the demo we load v1, then v2, then v1 again, each in a fresh loader that is closed afterwards:
== Hot reload: a fresh loader per version ==
  Hello from GreeterPlugin v1
  Hello from GreeterPlugin v2
  Hello from GreeterPlugin v1
  (the same class name, three times, three different Class objects)

== Unloading: a loader is collectable only when nothing reachable points into it ==
  plugin dropped, nothing else references it  -> loader collected: true
  plugin instance stored in static Registry   -> loader collected: false
  Registry cleared                            -> (new loader) collected: true
Both blocks are from output/05-plugins.txt. The middle line is the leak, and it is eight lines of code: a static list in the host that a plugin instance was added to (Registry.java):
private static final List<Plugin> KEEP = new ArrayList<>();

public static void register(Plugin p) {
    KEEP.add(p);
}
Follow the chain the garbage collector follows: the application loader owns Registry, which owns the list, which owns the plugin instance, whose class points to its loader, which points to every class it defined. One reference from a long-lived object into the plugin is enough to keep the whole loader and all its classes in memory. In a real server this shows up as OutOfMemoryError: Metaspace after enough redeploys, because class metadata lives in native memory outside the heap. Also note that the demo asks the collector politely (System.gc() in a bounded loop), since GC is a request: the “collected: true” lines passed on this run and in the contract test, but nothing in the Java specification forces a collection. The JVM can tell you what it unloaded. Running the same demo with -Xlog:class+unload gives the JVM’s own record (output/08-class-unload-log.txt):
      9 unloading class com.acme.GreeterPlugin
Nine GreeterPlugin classes were defined across the demo’s loaders, and the JVM logged nine unloads. The contract test goes one step further: it keeps the leaked loader, clears the registry, and asserts that the same loader is then collected.
Not only static lists. The demo reproduces the static-registry leak. Other roots commonly named in the literature (a ThreadLocal on a pooled thread, a thread the plugin started, a JDBC driver registered with DriverManager) hold the loader the same way, but this module does not reproduce them, so treat them as places to look rather than verified findings.

The thread context class loader: the escape hatch

Delegation only goes up. A library loaded by a parent loader (ServiceLoader, JDBC, JNDI) cannot see classes that only a child loader can see. The standard workaround is the thread context class loader: a loader stored on the current thread that such libraries consult. By default it is the application loader. ServiceLoader.load(Plugin.class) uses it, ServiceLoader.load(Plugin.class, loader) uses the loader you name:
== ServiceLoader.load(Plugin.class) uses the thread context loader (the app loader) ==
  context loader: 'app' (jdk.internal.loader.ClassLoaders$AppClassLoader)
  providers found: 0

== ServiceLoader.load(Plugin.class, pluginLoader) names the loader explicitly ==
    found com.acme.GreeterPlugin via 'plugin-ctx' (com.ankurm.classloaders.PluginLoader)
  providers found: 1
Source: ContextLoaderDemo.java; output: output/06-context-loader.txt. The provider was registered in a META-INF/services file inside the plugin’s directory. The default lookup found zero providers because the application loader cannot see that directory; naming the plugin loader finds one. The third way, setting the context loader around a call, also works in the demo, and the file shows it being restored in a finally, because forgetting to restore it is how a context loader ends up pinned to a thread that outlives the plugin.

Seeing it live: -Xlog and jcmd

You do not have to guess which loader defined something. -Xlog:class+load prints one line per loaded class with its source, and jcmd <pid> VM.classloaders prints the loader tree of a running JVM. This is the log for the classes from the first section:
java.lang.String source: shared objects file
java.util.ArrayList source: shared objects file
com.ankurm.classloaders.HierarchyDemo source: file:<module>/target/classes/
java.sql.Driver source: jrt:/java.sql
javax.tools.JavaCompiler source: jrt:/java.compiler
That is output/07-class-load-log.txt (the run script rewrites the absolute path to <module>). JDK classes come from the class-data-sharing archive or from jrt:/<module>, yours from file: or a jar. And this is the loader tree of HoldDemo, a JVM that keeps two named plugin loaders alive:
+-- <bootstrap>
      |
      +-- "platform", jdk.internal.loader.ClassLoaders$PlatformClassLoader
            |
            +-- "app", jdk.internal.loader.ClassLoaders$AppClassLoader
                  |
                  +-- "plugin-v1", com.ankurm.classloaders.PluginLoader
                  |
                  +-- "plugin-v2", com.ankurm.classloaders.PluginLoader
This is output/09-jcmd-classloaders.txt, trimmed of its process-id header line. It is the figure from the chain diagram with your own loaders hanging off the bottom, and it is the reason to name every loader you create: a named loader is the one you can recognise in the tree.

Should you write a class loader at all?

Usually no. If you need “drop in an implementation of an interface”, ServiceLoader already does that, with the default loaders. If you need isolation and versioned dependencies, an application server, a module layer (ModuleLayer), or separate processes are tested answers to the same problem, and they have had their leaks fixed by people whose full-time job it is. A hand-rolled loader earns its place when you genuinely need to load and unload code at run time, such as a plugin host or a code-generation tool, and then you own every problem on this page.

One more reason for caution, which I have not tested on JDK 25: the JDK 24 announcement for JEP 483 (ahead-of-time class loading and linking) said the AOT cache cannot hold classes from user-defined class loaders. Custom loaders sit outside the fast-startup path that the built-in ones can join. See JEP 483 and its follow-ups before depending on a custom loader in a startup-sensitive service.

Further reading

No Comments yet!

This site uses Akismet to reduce spam. Learn how your comment data is processed.