Kotlin ClassNotFoundException
Looking up an optional JVM class by name can fail when the class is absent from the runtime classpath.
A simple example
ClassNotFoundException
- Start with An optional component is absent
- Do this Try to look it up
- Result Unavailable
Syntax
Class.forName(name)
Run these examples in Kotlin
Save one example at a time as Lesson.kt. Use Kotlin 2.2 on JDK 21.
kotlinc Lesson.kt -include-runtime -d lesson.jar
java -jar lesson.jarLoad 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.
fun main() {
try {
Class.forName("example.optional.InvoiceExporter")
} catch (problem: ClassNotFoundException) {
println("Use the standard export")
}
}
Use the standard export
The optional exporter is absent from the standalone program. The standard export option remains available.
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.
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.
What to watch for
Use the fully qualified binary name. A failure to initialize a class that is present is a separate problem.