Files
java-core-examples/classloaders
..

classloaders

Companion code for the ankurm.com post "Java ClassLoaders Explained: Delegation, Custom Loaders, ClassNotFoundException vs NoClassDefFoundError." Module in java-core-examples, the Java-core series. All explanation lives in the post; this module holds the code and the captured output.

Versions this was built and tested against

Component Version Notes
JDK 25.0.5.1 (Temurin, LTS) Named loaders and getName() arrived in JDK 9; jcmd VM.classloaders in JDK 11.
JUnit Jupiter 5.11.0
Maven 3.9.11

Quickstart

export JAVA_HOME=/path/to/jdk-25
mvn compile
scripts/run.sh HierarchyDemo   # one demo
scripts/run-all.sh             # regenerate every file in output/

The demos compile the little plugin sources under plugins/ at run time with javax.tools, so the module needs a JDK (not a JRE) and must be run from the module directory.

What's in here

File What it shows Output
HierarchyDemo.java Which loader defined String, java.sql.Driver, your class and an array; the parent chain; modules per loader. output/01
DelegationDemo.java + DirLoader.java Parent-first delegation traced line by line across a two-loader chain. output/02
ForNameDemo.java loadClass and Class.forName(name, false, l) do not initialise; forName(name, true, l) does. output/03
ErrorsDemo.java ClassNotFoundException; NoClassDefFoundError from a deleted dependency; NoClassDefFoundError: Could not initialize class. output/04
PluginDemo.java + PluginLoader.java + Registry.java Class identity, the failing (Plugin) cast, hot reload, unloading and a leak. output/05
ContextLoaderDemo.java ServiceLoader and the thread context class loader. output/06
(JVM logging) -Xlog:class+load for the classes in demo 1. output/07
(JVM logging) -Xlog:class+unload while the unloading demo runs. output/08
HoldDemo.java A live JVM with two named plugin loaders, inspected with jcmd VM.classloaders. output/09
ClassLoaderContractTest.java Pins every claim above as an assertion. output/10
plugins/* The plugin sources the demos compile at run time (v1, v2, lib, uses-lib, missing, initfail, noisy).

License

MIT - see the repo-wide LICENSE.