1. Introduction to module-info.java
The Java Platform Module System (JPMS), introduced in Java 9, organizes Java code at a level above packages. A module can declare its dependencies, decide which packages are available to other modules, and describe how it participates in service-based designs.
The file responsible for declaring these rules is module-info.java. It is short, but it defines a contract between a module and the code that consumes it. The compiler reads the descriptor while compiling modular source code, and the compiled descriptor is stored as module-info.class. The runtime uses that information when resolving modules and enforcing their boundaries.
This lesson focuses on the descriptor itself: where it belongs, what can appear inside it, how each directive works, and how to build and run modular applications.
2. What module-info.java Actually Is
module-info.java is a special Java source file used to declare a module. It is not a normal class or interface. It cannot contain fields, constructors, methods, or a main method. Its body contains module directives defined by the Java language.
A minimal declaration looks like this:
The keyword module begins the declaration, com.example.cart is the module name, and the braces contain zero or more directives. An empty body is legal, although a useful application module normally needs to declare at least some dependencies or exports.
2.1 Where the file belongs
For a module named com.example.cart, a typical source layout is:
The module-info.java file sits at the root of the module's source tree, alongside the package directory. The package folders below it follow the normal Java package layout.
The module name does not have to match a top-level package name, but matching the package prefix is a widely used convention. It makes projects easier to understand and helps distinguish module names from the packages used in import statements.
2.2 Module naming conventions
Module names are usually lowercase and dot-separated, often following a reverse-domain naming convention such as com.example.cart. The purpose is to reduce the chance of two unrelated libraries using the same module name.
A module name identifies the module in directives and on the module path. A package name identifies a namespace of Java types. These names are related by convention, but they are not interchangeable.
2.3 From source descriptor to runtime metadata
The Java compiler translates module-info.java into module-info.class. The compiled descriptor carries the module name and its directives in a form the runtime can read. When the application starts in module mode, the runtime uses those declarations to resolve dependencies and enforce the module's package boundaries.
3. The Main Directives at a Glance
The body of module-info.java may contain several kinds of directives. Each directive describes a different part of the module's contract.
| Directive | Purpose |
|---|---|
requires M; | Declares a dependency on module M |
requires transitive M; | Declares a dependency and makes it readable to downstream consumers of this module |
requires static M; | Declares a compile-time dependency that may be absent at runtime |
exports p; | Exposes package p to modules that read this module |
exports p to M1, M2; | Exposes package p only to the named recipient modules |
opens p; | Allows deep reflection into package p at runtime |
opens p to M1, M2; | Allows deep reflection into package p for specified modules |
uses S; | Declares that the module consumes service type S |
provides S with I; | Declares that the module provides an implementation I of service S |
open module M { ... } | Opens all packages in the module for deep reflection |
A descriptor can contain multiple directives. A common layout groups dependencies first, then exports, reflective openings, and service declarations. The exact order is less important than making the module's contract easy to review.
4. Declaring Dependencies with requires
The requires directive declares that a module depends on another named module. For example:
This declares dependencies on java.sql and com.example.pricing. Code in the cart module can use accessible public types from those modules, provided the packages containing those types are exported appropriately.
A normal requires directive creates a readability relationship. If the cart module tries to use a type from a module it does not read, the compiler can report that the package is not visible or that the module does not read the module containing it.
4.1 Multiple dependencies
A module can declare multiple requires directives when it needs multiple modules. Each dependency should reflect a real need in the module's code or API. Unnecessary dependencies make the module graph larger and can make maintenance more difficult.
4.2 java.base is implicit
Every ordinary named module implicitly depends on java.base, which contains foundational types such as Object, String, and core collection APIs. Therefore, a descriptor does not normally need to contain:
The dependency is present even when the line is omitted.
4.3 Missing dependencies
A module being physically present on the module path is not enough on its own. A named module must declare the dependency relationship required by its code. If the descriptor omits a needed requires, compilation can fail because the consumer module does not read the module containing the imported type.
Module resolution also checks required modules at launch. Explicit dependencies make the intended structure visible rather than relying only on the accidental presence of JAR files.
5. The Module Dependency Graph
Each requires directive adds a relationship to the module graph. The application module depends on the modules it requires, and those modules may in turn depend on other modules. Every ordinary named module also implicitly depends on java.base.
The runtime resolves the modules required by the application. If a required module cannot be found, the application generally fails during module resolution or startup. JPMS also restricts cyclic dependencies between named modules; designs with cycles often benefit from extracting shared interfaces into a separate module or using a service-oriented boundary.
6. Re-exporting Dependencies with requires transitive
A plain requires directive makes a dependency readable to the module declaring it. It does not automatically make that dependency readable to modules that depend on it.
Consider a cart module whose public API exposes a type from the pricing module. A consumer that requires the cart module may need to use the pricing type in its own source code. If the cart module only declares a normal requires com.example.pricing, the consumer may also need to declare its own requires com.example.pricing.
requires transitive expresses that the dependency is part of the module's public-facing contract:
A downstream module that requires com.example.cart also gains readability to com.example.pricing through that transitive relationship.
6.1 When to use it
Use requires transitive when consumers of your module need to read another module because types from that dependency appear in your exported API. If a dependency is used only internally and does not need to be visible to consumers, a plain requires is generally more appropriate.
This directive should not be added automatically to every dependency. It affects the dependency contract and can make downstream modules read more modules than they otherwise would.
7. Optional Dependencies with requires static
The directive requires static declares a dependency that is required during compilation but may be absent at runtime.
The compiler can resolve types from com.example.annotations while compiling the module. At runtime, the module system does not require that dependency to be present in every deployment.
This is useful for dependencies that support compilation but are not always needed at runtime, such as some annotation libraries. It can also be appropriate for optional integrations when the application is designed to avoid those code paths if the optional module is absent.
7.1 Important runtime limitation
requires static does not magically make references to an absent dependency safe. If execution reaches code that needs a type from a missing module, the program can still fail, for example with NoClassDefFoundError. The application must be designed so that optional functionality is not used when the dependency is unavailable.
Use this directive deliberately. It relaxes the runtime requirement; it does not provide automatic feature detection or error handling.
8. Exposing Packages with exports
The exports directive controls which packages in a named module are available to other modules. By default, packages in a named module are not exported.
This exposes the public types in com.example.pricing.api to modules that read com.example.pricing. Other packages, such as com.example.pricing.internal, remain unexported unless they are separately listed.
8.1 public and exports work together
A class generally needs to be public for ordinary use by code in another package, and its package must be exported by the owning module for access by another named module. The public modifier alone does not make a type in an unexported package part of the module's external API.
This gives library authors a stronger way to separate stable API types from internal implementation details.
8.2 Exports operate at package level
An exports directive names a package, not a single class. Exporting com.example.pricing.api exposes the public API types in that package, but it does not automatically export its subpackages or other packages in the module.
A module's package layout should therefore reflect the boundary the author wants to maintain. Keep implementation classes in packages that are not exported when they are not intended for external use.
9. Qualified Exports with exports ... to
Sometimes a package should be accessible only to a small set of cooperating modules. Qualified exports provide that narrower boundary.
The first package is exported to all modules that read the pricing module. The second package is exported only to the named recipient modules.
Qualified exports can be useful for service-provider interfaces or internal integration points that need to be shared with specific modules without becoming a general public API. The recipient names in the to clause are module names, not package names.
10. Reflective Access with opens
The opens directive controls deep reflective access to a package at runtime. Reflection is used by frameworks that inspect fields, constructors, and methods dynamically. Ordinary package exports do not automatically grant deep reflective access to private members.
This opens the model package for deep reflection by other modules at runtime. It does not make the package ordinarily importable at compile time if it is not exported.
Frameworks used for serialization, dependency injection, and persistence may require reflective access to application classes. When deep reflection is blocked by module boundaries, an application can encounter InaccessibleObjectException.
10.1 exports versus opens
| Descriptor rule | Ordinary access from another named module | Deep reflection |
|---|---|---|
| No directive | Not available through module exports | Not granted |
exports p; | Public types in p can be accessed | Not automatically granted |
opens p; | Does not make p an exported API package | Granted at runtime |
Both exports p; and opens p; | Public API is exported | Deep reflection is also granted |
The two directives solve different problems. Use exports when a package is part of the module's ordinary API. Use opens when a framework needs reflective access that crosses normal Java access boundaries.
11. Qualified Opens with opens ... to
Like exports, opens can be qualified to restrict access to named modules:
This grants deep reflective access to the specified module rather than opening the package to every module. It is often the better choice when a particular framework needs reflective access but other consumers should not receive the same permission.
Reflective access should be granted as narrowly as practical. Opening an entire package exposes more internal state than exporting only its public API.
12. The open module Declaration
If a module is designed so that all its packages must be available for deep reflection, it can use an open module declaration:
An open module makes all packages in the module open for deep reflection at runtime. It does not automatically export all packages for ordinary compile-time access.
Because this grants broad reflective access, it should be used only when the module genuinely needs that behavior. If only one or two packages need reflection, individual opens directives—especially qualified ones—make the boundary more precise.
13. Service Loading: uses and provides
Java's service-provider mechanism allows code to discover implementations of an interface without naming each implementation directly. The standard ServiceLoader API can locate providers at runtime.
JPMS supports this model with two directives:
usesdeclares that a module consumes a service.provides ... with ...declares that a module supplies an implementation of a service.
The service interface is usually exported by its defining module. A provider module declares its implementation without needing to export the implementation package as part of its public API. The consumer depends on the service abstraction rather than on a particular provider.
13.1 Service interface module
The exported package contains the service interface:
13.2 Provider module
A provider module declares the service implementation:
The implementation class can remain in an unexported package. For the traditional class-based provider form, the provider implementation needs to meet ServiceLoader's instantiation requirements, commonly by providing a public no-argument constructor. A provider class can also use the supported public static provider-method form when appropriate.
13.3 Consumer module
The consumer declares that it uses the service:
Consumer code can discover available implementations using ServiceLoader:
The application does not need a direct compile-time dependency on the provider module. Another provider can be added to the runtime configuration without changing the consumer's service lookup code.
14. A Complete Two-Module Example
This example demonstrates the basic relationship between two explicit named modules: one module exports an interface, and another module requires it and calls it.
14.1 Project structure
14.2 Greeting module descriptor
src/com.example.greeting/module-info.java:
14.3 Greeting interface
src/com.example.greeting/com/example/greeting/Greeter.java:
14.4 Application module descriptor
src/com.example.app/module-info.java:
The application module declares the dependency it needs. The greeting module exports the package that contains the interface.
14.5 Application class
src/com.example.app/com/example/app/Main.java:
The example uses a lambda expression because Greeter has a single abstract method. The focus here is the module relationship: the application can import the interface because it requires the greeting module and the greeting module exports the interface's package.
14.6 Compile both modules
From the project directory, compile the source tree:
The --module-source-path option tells javac that the source tree contains module roots. The -d out option chooses where the compiler writes the class files. The shell command substitution shown here works in common Unix-like shells; on other shells, provide the source file paths using that environment's syntax.
14.7 Run the application module
The runtime reads the compiled descriptors, resolves com.example.app and its required com.example.greeting module, then invokes the main method. The output is:
If the greeting module is missing from the module path, the runtime cannot resolve the application's declared dependency. If the greeting package is not exported, compilation of the application's import fails even though the interface source exists.
15. A Complete Service-Loader Design
The service-loading design builds on the previous example by separating the API, provider, and consumer into distinct modules.
A typical structure is:
The API module exports the interface package. The English provider module requires the API module and declares provides. The application requires the API module and declares uses. At runtime, the service loader discovers providers that are present in the resolved module configuration.
This architecture separates three responsibilities:
| Module | Responsibility |
|---|---|
| Service API | Defines the interface or service contract |
| Provider | Implements the service and registers it with provides |
| Consumer | Uses the service interface and discovers implementations with ServiceLoader |
The benefit is reduced coupling. The consumer does not need to know the provider class name, and provider implementations can be replaced or extended without rewriting the consumer's service lookup.
16. Combining Directives in a Realistic Descriptor
A medium-sized module can combine multiple directive types. For example:
This illustrative descriptor shows several different contracts:
- The module re-exports its pricing dependency to downstream consumers.
- It depends directly on warehouse and database APIs.
- It marks an annotation-related dependency as optional at runtime.
- It exposes its public API package broadly.
- It exposes its SPI package only to specified cooperating modules.
- It opens its model package to a specific reflective consumer.
- It declares that it uses one service and provides an implementation of another.
Each directive has a distinct purpose. If a required dependency is missing, compilation or resolution may fail. If an API package is not exported, consumers cannot ordinarily access its public types. If a framework needs deep reflection and the package is not opened appropriately, reflective access may fail. If a provider declaration is removed, that implementation is no longer registered through the module's service-provider metadata.
In a real project, each module name and service type must refer to actual modules and types in the application. The example demonstrates the shape of a descriptor rather than a standalone project that can be compiled without those dependencies.
17. Common module-info.java Mistakes
17.1 Forgetting requires
An import may name a real type, but the compiler can still reject it if the module does not read the module that owns the package. Add the appropriate dependency to the descriptor and ensure that the required module is available.
17.2 Forgetting exports
A public class in a package that is not exported is not ordinarily accessible to another named module. Export the package only if it is intended to be part of the module's API.
17.3 Confusing module names and package names
A module name appears in module, requires, and qualified exports or opens clauses. A package name appears in directives such as exports and in source-code package and import declarations. Similar naming conventions do not make them the same identifier.
17.4 Opening a package when it should be exported
opens supports deep reflection but does not grant ordinary compile-time access to the package. If consumers need to import public API types, use exports. If a framework needs deep reflection, use opens; some designs need both.
17.5 Opening too much
An unqualified opens directive or an open module makes broad reflective access available. Prefer qualified opens when a known framework is the only component that needs this permission.
17.6 Cyclic module dependencies
If module A requires B and B requires A, the design has a dependency cycle that JPMS does not permit as a normal resolved module graph. Extract shared contracts into a third module or consider whether a service interface can reverse the direct dependency.
17.7 Split packages
The same package cannot be owned by multiple named modules in the same resolved configuration. Legacy libraries that spread a package across multiple JARs may need to be reorganized before they can be cleanly modularized.
17.8 Incorrect service provider configuration
The service interface must be accessible to the consumer, and the provider declaration must name the correct service and implementation. The implementation also has to satisfy ServiceLoader's provider-instantiation rules. A provider that cannot be instantiated can fail when the service loader attempts to discover or use it.
18. Useful Tools: jdeps and jlink
Two JDK tools complement the module descriptor.
18.1 jdeps
jdeps analyzes Java class files and JAR files to report dependencies. It can help developers understand what an existing application uses and plan a migration toward modules. It also supports generating a suggested module descriptor for some migration scenarios, which should be reviewed rather than accepted blindly.
A general command shape for inspecting dependencies is:
The exact options depend on whether the target is a module, a JAR, or a set of class files. Use the tool's help output for the installed JDK version when adapting the command to a project.
18.2 jlink
jlink assembles a custom runtime image from a set of modules and their dependencies. This can be useful for deployment when an application should run with a tailored Java runtime rather than relying on a full JDK installation being present on the target system.
A custom image must include the platform and application modules the application actually needs. Applications that dynamically discover features or depend on reflective behavior require particular care when deciding which modules to include.
Neither tool replaces the module descriptor. They help inspect or package the module structure declared by the application and platform.
19. How the Compiler and Runtime Use the Descriptor
The module descriptor participates in both compilation and execution, but in different ways.
During compilation, javac uses module names, dependency declarations, and exports to determine whether source code can refer to types in other modules. A missing dependency or an inaccessible package can therefore be reported before the program runs.
At runtime, the Java launcher locates modules on the module path, reads their compiled descriptors, resolves the module graph, and enforces module access rules. Reflective access is subject to the relevant opens rules as well.
The descriptor is not merely documentation. It is compiled metadata that the compiler and runtime use to enforce the module's declared contract.
20. Best Practices for Writing Module Descriptors
- Declare only real dependencies. Each
requiresdirective should represent a dependency the module needs. - Use
requires transitivewhen the dependency is part of the exported API. Avoid re-exporting internal implementation dependencies without a reason. - Keep exports narrow. Export only the packages that consumers are intended to use.
- Use qualified exports for targeted collaboration. This is useful for SPIs or integration packages intended for a known set of modules.
- Prefer qualified
openswhere practical. Grant reflective access to the framework that needs it rather than opening packages to everyone. - Treat
requires staticas an optionality contract. Ensure the application handles the absence of the dependency at runtime. - Use service interfaces to reduce implementation coupling. Keep providers replaceable and avoid direct consumer dependencies on implementation classes.
- Keep the descriptor organized. Group dependencies, exports, opens, and service declarations so reviewers can understand the module's contract quickly.
- Inspect actual dependencies during migration. Use tools such as
jdeps, then review the result against the intended design. - Compile and run using the module path during testing. A project may appear to work on the classpath while its module descriptor still contains missing or incorrect boundaries.
21. Quick Revision
module-info.javadeclares a named module and is compiled tomodule-info.class.- The file belongs at the root of the module's source tree.
requiresdeclares a dependency.requires transitivemakes a dependency readable to downstream consumers through the current module.requires staticmakes a dependency required at compile time but optional at runtime.exportsexposes a package's public API to modules that read the exporting module.exports ... torestricts an exported package to specified modules.opensgrants deep reflective access at runtime.opens ... tolimits that reflective access to specified modules.open moduleopens all packages for deep reflection.usesdeclares a service consumer.provides ... with ...declares a service provider.java.baseis implicitly required by ordinary named modules.jdepshelps analyze dependencies, whilejlinkcan build custom runtime images.- Module descriptors are enforced by the compiler and runtime; they are not merely documentation.
22. Conclusion
module-info.java is the central declaration file of an explicit Java module. It identifies the module and describes how it connects to the rest of the application. The requires family defines dependency relationships, exports defines the public package surface, opens controls deep reflection, and uses and provides support pluggable service architectures.
The strongest module descriptors are deliberate rather than maximal. They expose only intended APIs, declare the dependencies that are actually needed, and grant reflective access only where required. For simple modules, a descriptor may contain just a few lines. For larger libraries, it becomes a compact but important statement of the module's public contract and integration points.
Understanding these directives makes modular Java applications easier to compile, troubleshoot, maintain, and package. It also helps developers migrate from classpath-based projects without confusing package names, module names, ordinary visibility, and reflective access.