Library contents

Groovy ClassNotFoundException

Looking up an optional JVM class by name can fail when the class is absent from the runtime classpath.

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

Groovy syntax
Class.forName(name)
Run these examples in Groovy

Save one example at a time as Lesson.groovy. Use Groovy 4 on JDK 21.

groovy Lesson.groovy

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
Lesson.groovy
try {
    Class.forName("example.optional.InvoiceExporter")
} catch (ClassNotFoundException problem) {
    println("Use the standard export")
}
Output
Use the standard export

The optional exporter is absent from the standalone program. The standard export option remains available.

Advertisements

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

Handle an unavailable print adapter

A workstation lacks a school-specific optional adapter named in its settings. Try to load the configured component. A missing optional class selects the fallback.

Givenschool.example.OptionalPrinter
Worked resultUse fallback

What to watch for

Use the fully qualified binary name. A failure to initialize a class that is present is a separate problem.

Documentation for ClassNotFoundException