Introduction
Here, student.module is the name of the module.
The module declaration is written inside the module-info.java file.
requires
The requires keyword is used to declare a dependency on another module.
Here, student.module depends on the java.sql module.
exports
The exports keyword specifies which packages are accessible to other modules.
Here, the student package is exported and can be accessed by other modules that read this module.
Packages that are not exported remain encapsulated.
Example with requires and exports
A module can contain both requires and exports declarations.
This module:
- Depends on java.sql
- Makes the student package available to other modules
opens
The opens keyword allows reflective access to a package.
This is useful for frameworks and libraries that need to access classes and members through reflection.
uses
The uses keyword declares that a module uses a particular service.
It is commonly used with Java's Service Provider mechanism.
provides
The provides keyword declares an implementation of a service.
Here, StudentServiceImpl provides an implementation of StudentService.
Complete Example
A module descriptor can contain multiple declarations.
This file describes the module's dependencies, accessible packages, reflective access, and services.
Important Keywords
| Keyword | Purpose |
|---|---|
| module | Declares a module |
| requires | Declares a module dependency |
| exports | Makes a package available to other modules |
| opens | Allows reflective access to a package |
| uses | Declares a service used by the module |
| provides | Declares a service implementation |
Key Takeaways
- module-info.java is the module descriptor.
- It defines the structure and configuration of a module.
- requires defines dependencies.
- exports makes packages accessible to other modules.
- opens allows reflective access.
- uses and provides are used for Java's service mechanism.
- Each module has one module-info.java file.