Library contents

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

  1. Start with An optional component is absent
  2. Do this Try to look it up
  3. Result Unavailable
Detecting the missing component lets the program choose a built-in alternative.

Syntax

Java syntax
Class.forName(className)
Run these examples in Java

Save one example at a time as Main.java. Use JDK 21.

java Main.java

Load 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.

ResultUse the standard export
Main.java
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");
        }
    }
}
Output
Use the standard export

This standalone example has no optional exporter on its classpath. The billing application can still offer a standard export.

Advertisements

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.

ResultArrayList
Main.java
class Main {
    public static void main(String[] args) throws Exception {
        Class<?> available = Class.forName("java.util.ArrayList");
        System.out.println(available.getSimpleName());
    }
}
Output
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.

Givenjava.time.LocalDate
Worked resultComponent available
Code and output in Java
Java source
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");
        }
    }
}
Output
Component available

What to watch for

Check the configured name and runtime classpath. Other class-loading or initialization failures have different causes.

Documentation for ClassNotFoundException