How can I solve "java.lang.NoClassDefFoundError"?
java.lang.NoClassDefFoundError is an error that occurs when the Java Virtual Machine (JVM) can't find a required class definition at runtime. This can happen for a variety of reasons, including:
java.lang.NoClassDefFoundError is an unchecked error (a subclass of java.lang.Error, not Exception) that occurs when the JVM cannot find a required class definition at runtime, even though it was available at compile time. This differs from ClassNotFoundException, which is thrown when attempting to load a class dynamically by name (e.g., via Class.forName()).
Common causes and troubleshooting steps include:
- Missing from the classpath: Verify that the class file or JAR is included in your project's build path. In IDEs like IntelliJ or Eclipse, check
Project Structure>Modules>Dependencies. - Build path or compilation mismatch: Ensure the project is rebuilt after changes. Run
mvn clean compileorgradle clean buildto regenerate class files. - Missing dependency: If using Maven or Gradle, verify that all required libraries are declared in
pom.xmlorbuild.gradle. Check the dependency tree (mvn dependency:treeorgradle dependencies) to spot conflicts or missing transitive dependencies. - Class modified or deleted: If you recently refactored or removed a class, ensure all dependent classes are recompiled and the updated
.classfiles are in the output directory. - Corrupted or incompatible class file: A mismatched JDK version or corrupted
.classfile can trigger this error. Recompile with the correct JDK version and clean the build directory.
Example
// MissingDependency.java
public class MissingDependency {
public static void main(String[] args) {
// Throws NoClassDefFoundError if the library isn't in the classpath
System.out.println(new com.example.external.ExternalClass());
}
}Fix: Add the missing library to your build configuration. For Maven:
<dependency>
<groupId>com.example</groupId>
<artifactId>external-lib</artifactId>
<version>1.0.0</version>
</dependency>