Modules and the Module System
Domain 8 tests the module descriptor: how requires, exports and opens change compilation, runtime resolution, and reflective access.
Declaring a module
module-info.javasits at the source root:module com.example.app { requires java.sql; exports com.example.api; }.java.baseis required implicitly by every module and never needs to be declared.- Strong encapsulation hides non-exported packages at compile time and at runtime, not just by convention.
exports ... to a.bis a qualified export;opensgrants deep reflective access without exposing types at compile time.
Directives
requires transitivere-exports a dependency to any module that requires yours.requires staticis compile-time only: the dependency must be present to compile but is optional at runtime.usesandprovides ... withwireServiceLoaderimplementations.jdepsanalyzes dependencies;--module-pathreplaces the classpath for modular jars.
Classpath and unnamed modules
- Code on the classpath lands in the unnamed module and can read every module.
- A jar without
module-infoplaced on the module path becomes an automatic module, exporting all packages and reading all modules. Its name comes from the jar filename unlessAutomatic-Module-Nameis set in the manifest.
Worked example
module shop { exports shop.api; requires java.logging; }
A consumer declaring requires shop can use public types in shop.api only. Types in shop.internal stay inaccessible even via reflection unless shop declares opens shop.internal.
Traps
- Split packages (the same package in two modules) fail resolution.
--add-exportsand--add-opensare runtime workarounds, not design fixes.- A module cannot require itself, and cyclic
requiresrelationships are illegal.