java.lang.ClassNotFoundException
ID: java/classnotfoundexception
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| 17 | active | — | — | — |
Root Cause
ClassNotFoundException is thrown when the JVM attempts to load a class by name at runtime (via Class.forName(), ClassLoader.loadClass(), or reflection) and cannot find the class definition on the classpath.
genericWorkarounds
-
90% success Verify the JAR containing the class is on the runtime classpath and the dependency scope is correct
1. Identify which JAR provides the missing class (search Maven Central or use 'jar tf *.jar | grep ClassName'). 2. Check your build tool dependency declaration — ensure the scope is 'compile' or 'runtime', not 'provided' or 'test'. 3. For Maven: run 'mvn dependency:tree' to verify the dependency is included. For Gradle: run 'gradle dependencies'. 4. Ensure the dependency version matches what is expected (no exclusions removing it transitively).
-
85% success For modular Java (JPMS), ensure the required module is added to the module path and the package is exported or opened
1. Check if the application uses module-info.java. 2. Add 'requires <module-name>;' to your module-info.java for the module containing the class. 3. If the class is loaded via reflection, the target module must 'opens' the package to your module. 4. Alternatively, use --add-modules and --add-opens JVM flags to work around module encapsulation.
Dead Ends
Common approaches that don't work:
-
Adding the class source file to the project without ensuring the compiled class is on the runtime classpath
55% fail
The source file existing in the project does not mean the compiled .class file ends up in the runtime classpath. Build tool misconfiguration, missing dependency declarations, or incorrect packaging can cause the compiled class to be absent from the JAR or module path.
-
Hardcoding the fully qualified class name in Class.forName() without verifying the dependency is available at runtime
70% fail
The class may be a compile-time-only dependency (e.g., provided scope in Maven) or an optional dependency that is not included in the deployment artifact. Class.forName() will fail at runtime even though IDE autocompletion found the class during development.