W3docs

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:

  1. 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.
  2. Build path or compilation mismatch: Ensure the project is rebuilt after changes. Run mvn clean compile or gradle clean build to regenerate class files.
  3. Missing dependency: If using Maven or Gradle, verify that all required libraries are declared in pom.xml or build.gradle. Check the dependency tree (mvn dependency:tree or gradle dependencies) to spot conflicts or missing transitive dependencies.
  4. Class modified or deleted: If you recently refactored or removed a class, ensure all dependent classes are recompiled and the updated .class files are in the output directory.
  5. Corrupted or incompatible class file: A mismatched JDK version or corrupted .class file 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>