liveBook · Manning

Class loader

As explained in 100 Java Mistakes and How to Avoid Them

A class loader is a JVM component that locates, loads, and defines classes, with the defining loader contributing to a class's runtime identity.

A class loader locates, loads, and defines classes for the JVM. Runtime identity depends on both the class name and the defining loader, so equal names do not guarantee compatible types. section 5.3.3

Same name, different type

A URLClassLoader can load MyClass again from the application’s location. The resulting object prints as MyClass, but instanceof MyClass returns false and casting it throws ClassCastException because the two definitions use different loaders. section 5.3.3

Avoid the loader mismatch by following these rules:

  • Treat custom loaders as part of type design, especially in modular or plugin-based applications. section 5.3.3
  • Choose the parent loader carefully; parent-first delegation determines which dependencies are loaded by the parent. section 5.3.3
  • Prefer compatible shared types or interfaces, and avoid arbitrary casts across loader boundaries. section 5.3.3
import java.net.*;

public class MyClass {
  public static void main(String[] args) throws Exception {
    URL url = MyClass.class.getResource(".");    #1
    ClassLoader parent = System.class.getClassLoader();    #2
    try (URLClassLoader newLoader = 
           new URLClassLoader(new URL[]{url}, parent)) {
      Class<?> anotherMyClass = newLoader.loadClass("MyClass");
      Object o = anotherMyClass.getConstructor().newInstance();
      System.out.println("Class: " + o.getClass());
      System.out.println("Loader: " + o.getClass().getClassLoader());
      System.out.println("Instance of: " + (o instanceof MyClass));     #3
      MyClass cls = (MyClass) o;   #4
    }
  }
}

Inspect the minimal URLClassLoader example showing class loading, object creation, instanceof failure, and the cast that triggers ClassCastException. section 5.3.3

How 100 Java Mistakes and How to Avoid Them covers it

How deep it goes
Explains class identity, custom loading, parent-first delegation, and the resulting cast failure through a focused example.
Examples
Uses a second MyClass definition, instanceof, a cast, URLClassLoader, and the resulting exception message.
What you can do after
Diagnose loader-related cast failures and choose parent loaders more carefully when loading classes dynamically.
How it connects
Connects class identity to ClassCastException, URLClassLoader, parent delegation, modular architecture, and plugin support.

Also explained in

Compare how 2 books explain class loader →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of 100 Java Mistakes and How to Avoid Them. The section links point to the parts of the book it draws on.