Java ClassNotFoundException
Loading a class by its name throws ClassNotFoundException when the requested class cannot be found. This can happen with an optional runtime dependency.
A simple example
ClassNotFoundException
- Start with An optional component is absent
- Do this Try to look it up
- Result Unavailable
Syntax
Class.forName(className)
Run these examples in Java
Save one example at a time as Main.java. Use JDK 21.
java Main.javaLoad an optional invoice exporter
A billing application supports an optional exporter selected by class name. The workstation has only the standard installation, so the app should offer its built-in export format if the extra class is missing.
class Main {
public static void main(String[] args) throws Exception {
try {
Class.forName("example.optional.InvoiceExporter");
} catch (ClassNotFoundException unavailable) {
System.out.println("Use the standard export");
}
}
}
Use the standard export
This standalone example has no optional exporter on its classpath. The billing application can still offer a standard export.
Check the class name in a working configuration
A support engineer tests the class lookup mechanism before installing an optional exporter. A known standard class lets the engineer verify that the lookup reads a fully qualified name.
class Main {
public static void main(String[] args) throws Exception {
Class<?> available = Class.forName("java.util.ArrayList");
System.out.println(available.getSimpleName());
}
}
ArrayList
This lookup succeeds because java.util.ArrayList ships with the JDK.
Load the standard calendar component
The timetable editor is configured with the standard Java date class. Try to load the configured component. A missing optional class selects the fallback.
Code and output in Java
import java.util.*;
import java.io.*;
import java.nio.file.*;
import java.util.concurrent.*;
class Main {
public static void main(String[] args) throws Exception {
try {
Class.forName("java.time.LocalDate");
System.out.println("Component available");
} catch (ClassNotFoundException problem) {
System.out.println("Use fallback");
}
}
}
Component available
What to watch for
Check the configured name and runtime classpath. Other class-loading or initialization failures have different causes.