Diagnosing Missing requires Declarations
You'll learn how to interpret module resolution errors when your code references types from modules you haven't explicitly declared as dependencies.
The Problem
When you compile or run a modular Java application and forget to add a requires directive for a module your code depends on, the compiler or JVM will refuse to proceed. The error messages tell you exactly which module is missing from your module-info.java.
Understanding the Error Messages
At compile time, you'll see messages like:
error: package com.example.library is not visible
(package com.example.library is declared in module my.library,
which is not in the module graph)
This means your code imports or uses types from com.example.library, but your module descriptor doesn't include requires my.library;.
At runtime, you might encounter:
java.lang.NoClassDefFoundError: com/example/library/SomeClass
Caused by: java.lang.ClassNotFoundException
This indicates a missing runtime dependency that wasn't caught at compile time (often due to reflection or requires static issues).
The Fix
- Read the error carefully — it names the missing module
- Add the requires directive to your
module-info.java:
module my.app {
requires my.library; // Add this line
}
- Recompile and verify the error disappears
Think of It Like This
Imagine a library checkout system that tracks which books (modules) you've officially borrowed (declared in requires). If you reference a book you never checked out, the librarian (compiler) stops you and says, "You need to add that book to your checkout list first!"
Key Takeaway: Module resolution errors directly tell you which requires declaration is missing; add the named module to your module-info.java to resolve compilation and runtime issues.