The requires Directive: Basic Syntax
You'll learn how to use the requires directive in module-info.java to declare that your module depends on another module.
What Is requires?
The requires directive is how you tell the Java module system that your module needs another module to function. Think of it like declaring imports, but at the module level instead of the class level. While import statements bring in specific classes, requires makes an entire module accessible to your code.
Basic Syntax
Inside your module-info.java file, use requires followed by the module name:
module com.example.myapp {
requires java.sql;
requires java.logging;
}
This declares that your module com.example.myapp depends on two platform modules: java.sql and java.logging. Without these declarations, your code cannot access classes from those modules—the compiler will reject any attempts to use them.
How It Works
When you write requires java.sql;, you're saying: "My module needs everything that java.sql exports." Remember from previous lessons that modules use exports to make packages visible. The requires directive is the complementary piece—it creates a dependency edge in the module graph.
module com.example.orders {
requires com.example.products; // depends on custom module
requires java.base; // implicitly included, usually omitted
}
Every module automatically and implicitly requires java.base, so you typically don't write it explicitly.
Analogy
Think of modules as locked buildings. The exports directive unlocks certain doors for others to enter. The requires directive is your module asking for the key to enter another building's unlocked rooms.
Key Takeaway: Use requires <module-name>; in module-info.java to declare dependencies on other modules, enabling your code to access their exported packages.