SoFunction
Updated on 2025-03-01

Causes and analysis of NoClassDefFoundError in Java

ClassNotfoundException

Exceptions are often encountered in Java development. ClassNotfoundException exceptions usually cannot find the class during compilation, and the Console station will output exception information.

Generally speaking, we will rebuild or clean the project and let the project recompile.

The difference between two exceptions

However, when we encounter NoClassDefFoundError, we are sometimes easily confused with ClassNotfoundException exception.

Although the reasons for the NoClassDefFoundError and ClassNotfoundException exceptions appear similar, both because the class cannot be loaded through the compiled class, there are essential differences.

The essential difference between the two is:

  • ClassNotfoundException is caused by the JVM not loading the class or not finding the class during compilation;
  • NoClassDefError is that the JVM cannot load the class or find the class at runtime

NoClassDefFoundError Cause

Why does NoClassDefFoundError error occur?

In fact, it is related to the working principle of Java virtual machines. Here is a brief introduction to the JVM class loading mechanism

Three mechanisms of class loader: delegate, singleness, and visibility

  • Entrustment: refers to the request to load a class to be handed over to the parent class loader. If the parent class loader cannot be found or loaded, then load this class
  • Uniformity: means that the subclass loader will not load the class that the parent class loader has loaded again
  • Visibility: The subclass loader can see all classes loaded by the parent class loader, while the parent class loader cannot see the classes loaded by the subclass loader

The delegate line mechanism of the JVM class loading mechanism determines that the class loader is only loaded once, and the subclass loader will no longer load the classes that the parent class loader has already loaded.

All classes can be loaded at compile time under certain specific conditions, and classes cannot be loaded at runtime, and exceptions will occur.

NoClassDefFoundError may occur

Several situations have been found:

1. One situation is because the static variable cannot be loaded

2. If the jar is not added to the classpath or maven project in the project, it needs to be checked according to the project situation.

Summarize

The above is personal experience. I hope you can give you a reference and I hope you can support me more.