Sub topic 14
Class identity and common loading errors
This chapter assumes you know the loader hierarchy, parent delegation, and the load, link and initialize phases from the earlier chapters. You should also be able to compile and run small programs with javac and java. Here you will see how the JVM decides that two classes are the same class, and how that rule produces the errors you meet in production.
What makes a class the same class
At run time, a class is identified by two things: its fully qualified name and its defining class loader. The defining loader is the loader whose defineClass call created the class. A loader that only delegated to its parent is an initiating loader, not the defining one.
The JVM treats the pair as the identity. Two classes with the same name and byte-for-byte identical .class files are different types if different loaders defined them. They have separate static fields, separate static initializers, and no assignment compatibility.
This rule is deliberate. It lets an application server load two web applications that each ship their own copy of a library, without one copy interfering with the other.
Demonstrating the rule
Put a trivial class in a directory that is not on the application class path.
public class Target {
}Compile it into a plugins directory. The demo class below loads it by name, so it does not need Target at compile time.
import java.net.URL;
import java.net.URLClassLoader;
import java.nio.file.Path;
public class IdentityDemo {
public static void main(String[] args) throws Exception {
URL[] urls = { Path.of("plugins").toUri().toURL() };
ClassLoader platform = ClassLoader.getPlatformClassLoader();
try (URLClassLoader a = new URLClassLoader(urls, platform);
URLClassLoader b = new URLClassLoader(urls, platform)) {
Class<?> ca = a.loadClass("Target");
Class<?> cb = b.loadClass("Target");
System.out.println("same Class object: " + (ca == cb));
System.out.println("same name: " + ca.getName().equals(cb.getName()));
Object obj = ca.getDeclaredConstructor().newInstance();
System.out.println("cb.isInstance(obj): " + cb.isInstance(obj));
try {
cb.cast(obj);
} catch (ClassCastException e) {
System.out.println(e.getMessage());
}
}
}
}$ javac -d plugins Target.java
$ javac IdentityDemo.java
$ java IdentityDemo
same Class object: false
same name: true
cb.isInstance(obj): false
Cannot cast Target to TargetBoth loaders use the platform loader as parent. The platform loader cannot find Target, so each loader defines its own copy. The message "Cannot cast Target to Target" is the typical symptom of this problem. When a ClassCastException names the same type on both sides, suspect two loaders.
Initiating and defining loaders
The JVM records, per loader, which classes it has been asked to load, and it uses that record to keep names consistent. When class A refers to B, the JVM asks the loader that defined A to load B. If the loader gets the class from its parent, the parent is the defining loader and the child is only an initiating loader. Later requests for B through the child return the same Class object.
This is why the loading constraints work. If A and C are defined by different loaders and both refer to B, the JVM checks that both loaders resolve B to the same class. Otherwise it throws a LinkageError.
The following diagram shows two loaders, each with its own copy of Target.
Errors you will see
Loading problems appear as a small set of exceptions and errors. They differ in who throws them and what they mean.
| Throwable | Kind | Typical cause |
|---|---|---|
| `ClassNotFoundException` | Checked exception | An explicit lookup by name (`Class.forName`, `loadClass`) found nothing |
| `NoClassDefFoundError` | `LinkageError` | A class was present at compile time but is missing, or failed to initialize, at run time |
| `ExceptionInInitializerError` | `LinkageError` | A static initializer threw an unchecked exception |
| `ClassCastException` | Runtime exception | The object's class and the target type come from different loaders |
| `LinkageError` (duplicate definition) | Error | The same loader defined the same name twice |
| `NoSuchMethodError`, `NoSuchFieldError` | `IncompatibleClassChangeError` | The class found at run time has a different shape than the one compiled against |
ClassNotFoundException versus NoClassDefFoundError
ClassNotFoundException is the result of your own explicit request. You called Class.forName("com.example.Missing") or a framework did, and no loader could supply the bytes. You can catch it and recover, for example by trying a fallback.
NoClassDefFoundError comes from the JVM's implicit loading. Your code compiled, so the class existed then. At run time the JVM needed it for a new, a static call or a field access, and it could not be loaded. Often the ClassNotFoundException is attached as the cause.
To reproduce it, compile two classes, then delete one.
public class Main {
public static void main(String[] args) {
System.out.println("start");
System.out.println(new Helper().greet());
}
}
class Helper {
String greet() {
return "hello";
}
}$ javac Main.java
$ rm Helper.class
$ java Main
start
Exception in thread "main" java.lang.NoClassDefFoundError: Helper
at Main.main(Main.java:4)
Caused by: java.lang.ClassNotFoundException: HelperThe output "start" appears first because resolution is lazy. The JVM only loads Helper when it reaches the new instruction. In practice, this error means a missing JAR on the class path, a dependency marked as compile-only, or a class that exists but failed in its static initializer.
Failed initialization
The second cause of NoClassDefFoundError surprises people. A class whose static initializer throws is left in an erroneous state. The first use throws ExceptionInInitializerError, and every later use throws NoClassDefFoundError.
public class Errors {
static class Dep {
static int v = Integer.parseInt("x");
}
public static void main(String[] args) {
try {
Class.forName("com.example.Missing");
} catch (ClassNotFoundException e) {
System.out.println("CNFE: " + e.getMessage());
}
try {
System.out.println(Dep.v);
} catch (Throwable t) {
System.out.println(t);
}
try {
System.out.println(Dep.v);
} catch (Throwable t) {
System.out.println(t);
}
}
}CNFE: com.example.Missing
java.lang.ExceptionInInitializerError
java.lang.NoClassDefFoundError: Could not initialize class Errors$DepThe second error has no stack trace pointing at the real bug. When you see "Could not initialize class", search the logs for the earlier ExceptionInInitializerError. That first failure holds the real cause.
Duplicate definition
A single loader may define a given name only once. Calling defineClass twice with the same name on the same loader throws LinkageError: attempted duplicate class definition. This is why a custom loader should override findClass and leave loadClass alone. loadClass checks findLoadedClass first, so repeated requests never reach defineClass a second time. If you call defineClass directly from your own code, you must do that check yourself.
Mismatched versions
NoSuchMethodError means the class loaded at run time exists, but it does not have the method that your compiled code refers to. The usual cause is two versions of a library on the class path, where the loader picked the older one. Class path order decides which copy wins, because the first match is returned and later ones are never consulted.
Finding which loader supplied a class
Guessing is slow. Ask the JVM instead. Unified logging records each class as it loads, with its source.
$ java -Xlog:class+load:file=classload.log IdentityDemoSearch the log for the class name. A line such as Target source: file:/.../plugins/ tells you where the bytes came from. If the name appears twice, two loaders defined it.
You can also check from inside the program.
Class<?> c = obj.getClass();
System.out.println(c.getClassLoader());
System.out.println(c.getProtectionDomain().getCodeSource());getClassLoader() returns null for classes from the bootstrap loader, so guard against that. getCodeSource() can also be null for bootstrap classes.
A diagnostic routine
- Read the exact error type. It tells you whether the failure was an explicit lookup, an implicit one, or an initialization problem.
- For
NoClassDefFoundError, read the "Caused by" section. If it is absent and the message says "Could not initialize class", find the earlierExceptionInInitializerError. - For
ClassCastExceptionwith identical names, print both classes' loaders and code sources. - For
NoSuchMethodError, runjavap -con the class that the JVM actually loaded. Compare its method signatures with what the caller expects. - Confirm with
-Xlog:class+load, then fix the class path or the loader setup.
Exercise
In IdentityDemo, you change the two loaders so that both use IdentityDemo.class.getClassLoader() as parent, and you also add the plugins directory to the class path of the java command. What does ca == cb print, and why?
Show answer
It prints true. Parent delegation asks the application loader first. The application loader now finds Target on its class path and defines it once. Both child loaders receive that same Class object, so the application loader is the defining loader and the children are only initiating loaders.
Exercise
A program logs java.lang.NoClassDefFoundError: Could not initialize class Config on every request, but the first stack trace is gone from the logs. What happened to Config, and where do you look for the real cause?
Show answer
Config's static initializer threw an unchecked exception on first use. The JVM marked the class as erroneous, so every later use throws NoClassDefFoundError. Look for an earlier ExceptionInInitializerError in the log from the first access, or run the program with the class initialized early so the first failure is visible.