ClassLoader

A ClassLoader is a JVM component that loads Java classes at runtime — typically from .class files on the classpath, but also from network sources, encrypted storage, or generated bytecode. The ClassLoader hierarchy enables isolation (one app's classes can't accidentally leak into another's).

The default hierarchy

Bootstrap ClassLoader
    ↓ loads: java.* core classes from the JDK runtime image
Platform ClassLoader   (Java 9+, previously Extension ClassLoader)
    ↓ loads: standard JDK modules (jdk.*, java.sql, java.logging...)
Application (System) ClassLoader
    ↓ loads: classes from the -cp classpath

Parent-first delegation

When asked to load a class, a ClassLoader first delegates to its parent. Only if the parent cannot find the class does it attempt to load it itself. This prevents user code from overriding core JDK classes with malicious replacements.

Getting the current ClassLoader

ClassLoader cl = MyClass.class.getClassLoader();
System.out.println(cl);
ClassLoader parent = cl.getParent();

Custom class loaders

Frameworks like web application servers (Tomcat, Jetty) use custom ClassLoaders to isolate each deployed application. OSGi bundles and JPMS modules build on this mechanism. You rarely need to implement a ClassLoader yourself.

ClassNotFoundException vs NoClassDefFoundError

  • ClassNotFoundException — thrown by Class.forName() when the class is not on the classpath at runtime.
  • NoClassDefFoundError — thrown when the JVM tried to link a class that was present at compile time but is now missing.