← Debugging Guides

阅读中文版本

Java — NoClassDefFoundError at runtime though the class compiled

Fix NoClassDefFoundError by finding why a class present at compile time is missing or failed at runtime.

intermediatedebuggingjavabuild

Symptoms

  • java.lang.NoClassDefFoundError: com/example/Helper
  • It works in the IDE but fails from the built jar
  • The error names a class that exists in the source
  • A static initializer failure precedes the error

Possible causes

  • The class is absent from the runtime classpath or packaged jar
  • The class failed during static initialization earlier
  • A dependency provides the class only at compile scope
  • The jar was built without the needed dependency

Diagnosis steps

Check whether the class is in the runtime artifact

jar tf app.jar | grep Helper.class

Interpretation

If the class is missing from the jar, the build excluded it or the dependency scope is wrong.

Look for an earlier initialization error

App 2>&1 | grep -B5 NoClassDefFound

Interpretation

A preceding ExceptionInInitializerError means the class exists but its static block failed, which surfaces later as NoClassDefFoundError.

Verify dependency scope

mvn dependency:list -DincludeScope=runtime

Interpretation

A provided or compile-only scope keeps a dependency out of the runtime classpath.

Root cause

The class was available at compile time but not at runtime, either because it is missing from the runtime classpath or because its static initialization failed on an earlier attempt.

Fix

Include the missing dependency in the runtime classpath or fat jar, correct the dependency scope, and fix the static initializer failure that caused the class to be unloadable.

Verify the fix

Run the built artifact again and confirm the class loads, and confirm no preceding initializer error remains.

Symptom walkthrough

A program compiles but throws NoClassDefFoundError at runtime for a class that clearly exists in the source. Either the class is missing from the runtime classpath or jar, or its static initialization failed earlier and the runtime reports the later use as a missing class. The distinction matters, because a prior ExceptionInInitializerError points at the initializer rather than at packaging.

Fix in practice

Ensure the dependency is on the runtime classpath, correct its scope so it is packaged for runtime, and fix any static initializer that threw. Building a fat jar that includes runtime dependencies prevents the classpath portion of this error.

Verification

Run the built artifact again and confirm the class loads, then confirm no earlier initializer error appears in the logs. A clean load without a preceding initialization failure confirms the fix.

Diagnostic commands

Check the behavior with commands like these:

jar tf app.jar | grep Helper.class
App 2>&1 | grep -B5 NoClassDefFound
mvn dependency:list -DincludeScope=runtime