Java 9 Module System: Boundaries, Encapsulation, and requires/exports
A guide to the Java 9 Module System covering module boundaries, strong encapsulation, the requires and exports directives, and practical migration patterns.
A guide to the Java 9 Module System covering module boundaries, strong encapsulation, the requires and exports directives, and practical migration patterns.
Java 9 Module System: Boundaries, Encapsulation, and requires/exports
The Java Platform Module System (JPMS), introduced in Java 9, adds named modules above packages. A module descriptor declares dependencies and which packages it exports or opens. The module path and classpath remain separate ways to launch applications; using a JDK after Java 9 does not require every application to adopt module-info.java.
The examples use Java SE 25 terminology and behavior. The module system controls readability, exported APIs, and reflective access between modules. It does not sandbox untrusted code or restrict a program’s access to files, processes, or the network. For current module rules, see the Java Language Specification, Chapter 7 and Oracle’s JDK 8 migration guide. For JVM background, see JVM Architecture Overview and bytecode verification.
Introduction
The JPMS is part of the Java platform, but an application can continue to run on the classpath without declaring its own named modules. When you use the module path, a JAR with module-info.class is an explicit module; a JAR without a descriptor can be treated as an automatic module. A classpath JAR belongs to the unnamed module. These modes have different readability and encapsulation rules.
Modules matter when you want explicit dependencies, a defined public package surface, service declarations, or a custom runtime image. During migration, module resolution and access failures can appear at compile time, startup, or reflective access depending on the missing requirement. Reflection into a package may need a targeted opens directive or a temporary --add-opens launcher option. On JDK 17 and later, strong encapsulation of JDK internals is the default; the exact exception for failed reflective access is commonly InaccessibleObjectException.
This post covers module descriptors, exports and opens, module-path and classpath behavior, service declarations, and migration pitfalls. It also explains the limits of module encapsulation so it is not mistaken for a security sandbox.
When to Use Modules
Java 9 introduced JPMS. JDK 25 continues to support both modular applications and classpath applications. Use a descriptor when its explicit boundaries or service declarations help the application; do not add one solely because the JDK is modular.
Cases where understanding the module system is essential:
- Designing explicit module boundaries for an application or library
- Migrating a large codebase from Java 8 to a newer version
- Using libraries that have their own module descriptors (module-info.java)
- Running on a minimal JVM image created with jlink
- Diagnosing NoClassDefFoundError or IllegalAccessError in Java 9+ environments
Cases where modules largely stay out of your way:
- Simple applications where all code lives in a single module or no modules at all
- Running on Java 8 or earlier (no migration planned)
- Using only the classpath for a classpath-based application
When NOT to Use
The module system adds descriptors and dependency rules. Use it when named boundaries or service declarations solve a real maintenance problem; otherwise, a classpath deployment remains a supported option.
For small applications without a module-boundary need. If the classpath already describes the application clearly, adding module-info.java may add maintenance without helping its users.
When the classpath already fits. If the application does not need module boundaries or service declarations, the classpath remains supported. A classpath JAR is part of an unnamed module; it does not become an automatic module just because it runs on a modern JDK.
For rapid prototyping and small team projects. Module descriptors require upfront thinking about exports, requires, and boundaries. In a prototyping phase where the architecture is still shifting, module-info.java files become refactoring work that may not pay off before the code changes again. Use the classpath for exploration, adopt modules when the architecture stabilizes.
When dealing with libraries that have split packages. Two explicit named modules cannot define the same package in one module graph. A classpath-based deployment may avoid that module-path restriction, but it keeps code in the unnamed module rather than providing named-module boundaries.
Module Anatomy
A module is defined by a module-info.java file placed at the root of a module’s source tree. This file lives alongside the packages that make up the module.
graph TD
A[myapp.auth<br/>module-info.java] -->|requires| B[myapp.core]
A -->|requires| C[java.base]
B -->|requires| C
A -->|exports| D[com.myapp.auth.api]
B -->|exports| E[com.myapp.core.api]
A -.->|uses| F[com.myapp.auth.spi]
B -.->|provides| G[com.myapp.core.spi<br/>with com.myapp.core.impl]
F -.->|implementation| G
C -->|exports| H[java.base<br/>packages only]
The module descriptor declares dependencies (requires), packages available to other modules (exports and opens), and service use or implementation (uses and provides). exports grants ordinary access to public types and members in a package. opens grants runtime reflective access, including deep reflection, without making the package available for ordinary compile-time use.
A Simple Module Descriptor
// module-info.java
module com.myapp.auth {
// This module needs the core module at compile and runtime
requires com.myapp.core;
// These packages are accessible to any module that requires com.myapp.auth
exports com.myapp.auth.api;
exports com.myapp.auth.model;
// This module uses the password encoder service
uses com.myapp.auth.spi.PasswordEncoder;
// This module provides a concrete implementation of that service
provides com.myapp.auth.spi.PasswordEncoder
with com.myapp.auth.internal.BCryptEncoder;
}
requires com.myapp.core declares a module dependency. The exports lines expose two packages to modules that read com.myapp.auth; com.myapp.auth.internal remains unexported. Exporting a package is not a permission to access every private member: normal Java access rules still apply.
uses and provides handle service discovery. uses says this module needs a PasswordEncoder. provides with with says BCryptEncoder is the implementation. ServiceLoader.load(PasswordEncoder.class) finds it at runtime without either side having a compile-time dependency on the other.
For compilation, put module-info.java on the module source path with your Java files. Package the result as a modular JAR, keeping module-info.class at the JAR root. Run it on the module path. Without a descriptor, the application can run on the classpath as part of the unnamed module; classpath access rules differ from named-module rules.
The exports Directive
exports controls which packages are visible to other modules. Only packages named in an exports directive can be accessed from outside the module.
module com.myapp.database {
// Public API accessible to any module
exports com.myapp.db.api;
exports com.myapp.db.query;
// Qualified export - only accessible to specific modules
exports com.myapp.db.internal to com.myapp.reporting, com.myapp.analytics;
// Not exported - only accessible within the module
// com.myapp.db.impl is invisible to other modules
}
Qualified exports (exports ... to ...) let you restrict visibility to specific modules. This is useful when a package contains APIs needed by a small set of known consumers but you do not want to make it broadly available.
Other modules cannot use a non-exported package through ordinary access. An illegal access may be rejected by the compiler or at runtime, depending on how the code was produced and launched.
The requires Directive
requires declares a dependency on another module. The dependent module gets read access to all exported packages of the required module.
module com.myapp.web {
// Standard dependency on the web framework
requires spring.web;
// Static dependency - needed at compile time but not runtime
// Useful for annotation processors and compilers
requires static lombok;
// Transitively required - com.myapp.web automatically gets
// access to what spring.web requires
requires transitive spring.core;
// Self-dependency is not allowed
// requires com.myapp.web; // COMPILE ERROR
}
The transitive modifier is important. When module A requires transitive module B, any module that requires A also automatically requires B. This propagates dependencies correctly through the module graph.
requires static is a lesser-known feature. Use it for dependencies that are only needed at compile time, such as annotation processors. The dependency is not enforced at runtime.
The Service Loader Pattern
Modules integrate with ServiceLoader through the uses and provides directives. This allows for loose coupling between a service interface and its implementation.
// In the module that defines the service interface
module com.myapp.auth {
exports com.myapp.auth.spi;
uses com.myapp.auth.spi.PasswordEncoder;
}
// In the module that provides the implementation
module com.myapp.auth.bcrypt {
requires com.myapp.auth;
provides com.myapp.auth.spi.PasswordEncoder
with com.myapp.auth.bcrypt.BCryptEncoder;
}
// Using the service in application code
ServiceLoader<PasswordEncoder> loader = ServiceLoader.load(PasswordEncoder.class);
Optional<PasswordEncoder> encoder = loader.findFirst();
The uses directive in the service consumer module and the provides directive in the service implementation module are both required. Neither side needs to know about the other at compile time, which makes this pattern useful for plugins and optional components.
unnamed Modules and Automatic Modules
When a JAR without module-info.class is placed on the module path, it can be treated as an automatic module. Its module name comes from Automatic-Module-Name when supplied, otherwise from the JAR name; it exports all packages and has broad readability. A JAR placed on the classpath belongs to the unnamed module instead.
# Running with modules
java --module-path mods:lib -m com.myapp/com.myapp.Main
# Running a classpath application
java -cp 'lib/*:app.jar' com.myapp.Main
The classpath is still supported. Code on the classpath belongs to the unnamed module, which has broad readability and exports its packages. Explicit modules enforce the boundaries declared in their descriptors.
Named modules can read automatic modules located on the module path when declared as dependencies. The classpath’s unnamed module has different readability rules. Keep the terms distinct when diagnosing migration problems: classpath JAR, automatic module, and explicit named module are not interchangeable.
Production Failure Scenarios
| Failure Scenario | Symptoms | Root Cause | Solution |
|---|---|---|---|
| Split package across modules | Error: package X appears in both module A and module B | Two modules claim the same package | Move classes or merge modules |
| Missing dependency | Resolution or class-loading error | Dependency absent from the selected path or graph | Check the module path and descriptor |
| Export to unavailable module | Compile or access error | Qualified export does not include caller | Fix the target module list |
| Module resolution failure | FindException or ResolutionException | Required module missing or graph conflicts | Check module path and descriptors |
| Missing static dependency at compile time | Compile-time module-not-found error | requires static dependency absent from the compile module path |
Add the dependency to the compile module path |
| Service provider not discovered | ServiceLoader returns empty | Provider module missing provides directive | Check module-info of provider |
Trade-off Analysis
Understanding the costs and benefits of the module system helps you decide where to invest migration effort.
| Concern | Module path | Classpath |
|---|---|---|
| Dependency graph | Named modules declare requires; automatic modules have inferred names and broad readability. |
JARs belong to the unnamed module. Dependencies are generally assembled by the launch configuration. |
| Package access | Named modules expose packages through exports and reflective access through opens. |
There are no named-module package boundaries between classpath JARs. Java language access rules still apply. |
| Runtime image | jlink can assemble a custom runtime for a modular application. |
A custom jlink image requires modules; classpath applications usually use a regular JRE or JDK runtime. |
| Migration | Requires checking descriptors, dependencies, split packages, and reflective access. | Often avoids JPMS migration work, but does not provide named-module boundaries. |
Implementation Snippets
Building a Multi-Module Project
# Directory structure for a multi-module project
# myapp/
# modules/
# auth/
# module-info.java
# com/myapp/auth/*.java
# core/
# module-info.java
# com/myapp/core/*.java
# build.sh
# Compile each module to a separate output directory
mkdir -p out/auth out/core
# Compile core first
javac -d out/core \
--module-source-path modules \
modules/core/module-info.java \
modules/core/com/myapp/core/api/*.java \
modules/core/com/myapp/core/spi/*.java
# Compile auth, which depends on core
javac -d out/auth \
--module-source-path modules \
--module-path out/core \
modules/auth/module-info.java \
modules/auth/com/myapp/auth/api/*.java \
modules/auth/com/myapp/auth/internal/*.java
# Create modular JARs
jar --create --file=lib/auth.jar \
--main-class=com.myapp.auth.AuthService \
-C out/auth .
jar --create --file=lib/core.jar -C out/core .
# Run with the module path
java --module-path lib -m com.myapp.auth/com.myapp.auth.AuthService
Migrating a Classpath Application
Migrating a classpath application to modules can proceed bottom-up. Your own code can become a named module while dependencies remain on the module path as explicit or automatic modules. jdeps can help inspect dependencies and generate a descriptor template for a suitable JAR; review its output before adopting it.
The order matters. Start with your own module boundaries and check whether third-party libraries already ship descriptors. A JAR without one can be an automatic module when placed on the module path; a JAR on the classpath belongs to the unnamed module. The choice affects readability and encapsulation, so verify the actual launch command rather than treating the terms as synonyms.
For deep reflection, the target module must open the package to the caller, or the launch command must grant a targeted --add-opens access. Failed reflective access can throw InaccessibleObjectException. Use a narrowly scoped open for a documented framework need; avoid opening packages broadly.
// Step 1: Create module-info.java for your app
module com.myapp {
// Declare what you need from the JDK
requires java.sql;
requires java.logging;
// Declare what you need from third-party libraries
// Named or automatic modules on the module path can be required by name.
requires com.google.guava;
// Export your public API
exports com.myapp.api;
exports com.myapp.service;
}
// Step 2: Handle internal packages
// Any package not exported is automatically internal
// Move classes that should be internal to non-exported packages
// Step 3: Handle reflection
// If you use reflection on private members, you may need opens
opens com.myapp.internal to com.google.guava;
opens com.myapp.internal to com.myapp.testing;
Using jlink to Create a Minimal Runtime
jlink builds a custom runtime image from selected modules. Its size depends on the JDK distribution, selected modules, native libraries, and application contents; measure the image for your target platform rather than assuming a fixed size.
The requirements are modular JARs on the module path and $JAVA_HOME/jmods as your JDK module path. --add-modules specifies which modules to include, pulling in transitive dependencies automatically. --launcher creates a start script with the correct module path and main class already configured.
The resulting image includes the selected modules and their dependencies for the target platform. A custom runtime can reduce the JDK components shipped with an application, but it is not a sandbox. Build and inspect the image for the operating system and architecture where it will run.
# After building your modular JARs
# Create a minimal runtime image with just the modules you need
jlink --output myapp-runtime \
--module-path lib:$JAVA_HOME/jmods \
--add-modules com.myapp.auth,com.myapp.core,java.base \
--launcher start=com.myapp.auth \
--vm=server
# The resulting runtime only includes:
# - The JDK modules your app actually uses
# - Your application modules
# - A custom launcher script
./myapp-runtime/bin/start
Observability Checklist
When running module-aware applications in production, here is what to watch.
- Monitor for module access errors and
InaccessibleObjectExceptionduring reflective access - Use
-Xlog:module=infowhen module-resolution logging is needed - Track NoClassDefFoundError patterns that suggest missing requires
- Verify dependency module names and descriptors on the selected module path
- On JDK 17+, remove reliance on the obsolete
--illegal-accessoption; it has no effect beyond a warning - Audit uses of
opensandadd-opensfor security and stability implications - Measure startup and memory use on the target runtime after a module-path migration
- Monitor for Layer-related errors during dynamic module loading
Security Notes
The module system changes how reflection works. By default, modules restrict reflective access to unexported members. If you need to access private fields or methods via reflection, you must explicitly open the package or module.
// Before Java 9, this worked on the classpath:
// Field field = MyClass.class.getDeclaredField("internalState");
// field.setAccessible(true);
// Deep reflection into a non-open package can fail with InaccessibleObjectException.
// Open only the package that a trusted framework or test module needs:
module com.myapp {
opens com.myapp.internal to com.myapp.testing;
opens com.myapp.internal to com.myapp.serialization;
}
// Or open to ALL modules at once:
module com.myapp {
opens com.myapp.internal; // Opens to reflection but not to compile-time access
}
The --add-opens JVM option grants runtime reflective access to a selected package and target module without changing the descriptor. Treat it as a compatibility measure for a specific dependency, not as a general module configuration. JPMS encapsulation is not a sandbox: it does not prevent code from using the operating system’s file, process, or network APIs when the process has those permissions.
The Java Security Manager is not an alternative control for new Java applications. JEP 486 permanently disables it in Java 24 and later. Use operating-system isolation, container or VM boundaries, and least-privilege process credentials when the goal is to restrict untrusted code; module exports and opens solve a different problem. See JEP 486.
Common Pitfalls / Anti-Patterns
Here are the most common mistakes when working with the Java Module System.
Split packages. Two explicit named modules cannot contain the same package in one module graph. Repackage or combine the classes if you need both as named modules. Keeping code on the classpath changes it to the unnamed module; it does not make that JAR an automatic module.
Confusing module-path and classpath dependencies. A no-descriptor JAR on the module path can be an automatic module. The same JAR on the classpath is part of the unnamed module. Check the launch configuration and module readability rules before changing opens or adding command-line flags.
Over-exporting. Exporting every package is tempting but defeats the purpose of encapsulation. Start by exporting nothing, then add exports only when another module genuinely needs access.
Opening packages broadly. opens grants deep runtime reflection. Restrict it to named consumers when possible and do not confuse it with a sandbox or permission system.
Forgetting that module names matter. Module names must be unique in the module graph. They do not have to match package names or JAR names. Use reverse-domain naming like com.myapp.auth for consistency.
Quick Recap Checklist
Use this checklist when migrating to or working with the Java Module System.
- Audit your JARs for split packages before migration
- Create module-info.java for your application module
- Declare all JDK and third-party dependencies with requires
- Export only the packages that form your public API
- Move internal classes to non-exported packages
- Use qualified exports for packages needed by specific consumers
- Remove obsolete
--illegal-accessflags from current JDK launch configurations - Use
opensor targeted--add-opensonly for documented reflective access - Consider jlink for smaller distribution footprints
- Use ServiceLoader with uses/provides for plugin architectures
Interview Questions
requires declares that your module depends on another module, giving you read access to that module's exported packages. requires transitive does the same but also propagates the dependency to any module that requires your module. If module A requires transitive B, and module C requires A, then C automatically reads B as if it had declared requires B itself. This is how you propagate dependencies correctly through a module graph without forcing every downstream consumer to declare them explicitly.
Named modules make dependencies and exported packages explicit and can be used to build custom runtime images with jlink. They are a code organization and encapsulation feature. They do not restrict operating-system access or provide a sandbox for untrusted code.
An automatic module is a JAR without module-info.class placed on the module path. It has a derived or manifest-specified name, exports all its packages, and has broad readability. A JAR on the classpath belongs to the unnamed module instead. Named modules can require an automatic module on the module path; check the JLS and launcher configuration for the exact module graph.
The opens directive grants runtime reflective access to a package without exporting it for ordinary compile-time use. It can name specific consumer modules, or an unqualified opens grants access to all modules. If reflective access is not permitted, Java can throw InaccessibleObjectException. Use the narrowest opening that satisfies a documented framework or test requirement.
A split package has classes with the same package name in multiple JARs. Explicit named modules in one module graph cannot split a package. To modularize them, merge or repackage the classes; alternatively keep the dependency arrangement on the classpath and accept that it is not a named-module boundary.
Module loading follows a specific order: first the java.base module is loaded, then all other modules are loaded based on their requires directives in topological order. A ClassLoader that loads a module must have all its requires dependencies visible. This means if module A requires B, the ClassLoader loading A must also be able to load B. If you have a custom ClassLoader and it tries to load a module without having access to its dependencies, you get NoClassDefFoundError. This is different from the classpath where all classes are visible to all ClassLoaders.
A named module has an explicit module-info.class and is resolved on the module path. An automatic module is a no-descriptor JAR on the module path; its name is derived from its filename or manifest and its packages are exported. The unnamed module contains code on the classpath and has broad readability and exports. The classpath and module path are distinct deployment choices.
exports without qualification makes a package accessible to all modules. exports...to (qualified export) makes a package accessible only to the listed modules. You use qualified exports when a package contains APIs needed by specific known consumers but you do not want to make it broadly available. For example, internal testing utilities might be exported only to a testing module. The compiler and JVM enforce this: if a module not in the to-list tries to import classes from a qualified-exported package, it gets an IllegalAccessError at both compile time and runtime.
provides declares that a module implements a service interface, and with specifies the concrete implementation class. For ServiceLoader to discover the provider, both the service consumer module (with uses) and the service provider module (with provides) must be on the module path. The provider module must declare provides ServiceInterface with ImplementationClass. The consumer module must declare uses ServiceInterface. At runtime, ServiceLoader.load(ServiceInterface.class) iterates through the module layers to find modules that declare provides ServiceInterface.
JDK 9 through 16 used --illegal-access as a migration aid for reflective access to JDK internals. It became obsolete in JDK 17; in JDK 17 and later it has no effect other than a warning. Oracle's JDK 25 migration guide recommends targeted --add-exports or --add-opens only when a legacy tool requires access. Prefer updating the dependency or using a supported API.
Reflection remains subject to Java access rules and module boundaries. Deep reflection into a package in another module requires that package to be open to the caller, through an opens directive or a targeted --add-opens option. Without it, setAccessible(true) can throw InaccessibleObjectException. Classpath code has different module boundaries, but it is not a security sandbox.
requires declares a dependency that must be present at both compile time and runtime. If the required module is not available, the JVM refuses to start or the compiler fails. requires static declares a dependency that must be present when compiling the module but need not be present at runtime. This fits optional dependencies used only by compile-time tools, such as some annotation-processing APIs. It is a distinct modifier from requires transitive.
Choose one deployment model deliberately. A dependency JAR on the classpath is part of the unnamed module; a no-descriptor JAR on the module path can be an automatic module and be required by a named module. Do not use --add-opens to fix a missing module dependency; it controls reflective access, not readability.
A missing module on the module path is usually reported as a resolution error such as `FindException` at launch; missing classes can instead surface later as `NoClassDefFoundError`. Check the module name, the selected module path, and each declared dependency. Use `--module-path` to locate modules and `--add-modules` when the initial module set needs to be specified.
jdeps is a command-line tool that analyzes class and JAR files for dependencies. It can generate module-info.java templates based on the JAR's manifest or class contents. It identifies internal API usage, suggests replacements from the Java Platform Module System, and shows which modules are required. For migration, run jdeps --generate-module-info on your classpath JARs to generate module descriptors, then review and refine them. jdeps can also identify uses of --add-opens and suggest proper module declarations to replace them.
Modules loaded by the system ClassLoader (the application class loader) participate in the module system normally. Modules loaded by custom ClassLoaders create their own module layers within the JVM. Each ClassLoader can define modules, and modules from different ClassLoaders are isolated from each other. A module defined by one ClassLoader cannot read modules from another ClassLoader unless there is an explicit module layer relationship. This isolation affects ServiceLoader discovery, which searches within module layers.
An `opens` directive allows deep reflection into a package at runtime without exporting it for ordinary source access. It can be qualified for named consumers. An `open module` applies that reflective opening to all packages. Neither form turns those packages into ordinary exported APIs.
Use the --module-path option with a colon-separated list to ensure all modules are found. Use --add-modules to specify the initial module to resolve. Use -Xlog:module=info to see detailed module resolution logging. If a split package error occurs, use --module-path to list all modules and identify which JARs contain conflicting packages. The jdeps tool can show you the full dependency graph before you try to run. For cyclic dependencies, the JVM detects them during resolution and reports LayerInstantiationException with a cycle description.
No, a package can only be exported once with specific visibility. You cannot export a package to module A and export it differently (e.g., more restricted) to module B. Either the package is exported to all modules (exports package), exported only to specific modules (exports package to moduleA, moduleB), or not exported at all. The export declaration applies to all modules that require the exporting module. To have different visibility for different consumers, you would need to restructure the packages, for example by having an API package and an internal package.
A Layer represents a group of modules loaded by the same ClassLoader or that have a defined relationship. The JVM creates a Layer for each module path or ClassLoader configuration. The system Layer is the base layer containing java.base and other JDK modules. When you create a custom ClassLoader that defines modules, you can create a new Layer above the system Layer. Layers can have parent Layers, and module resolution traverses parent Layers to find dependencies. Layers are hierarchical and allow multiple module configurations to coexist in the same JVM.
Further Reading
- Advanced Java & JVM Internals Roadmap — Parent roadmap covering all JVM internals topics
- JEP 486: Permanently Disable the Security Manager — Java 24 behavior and rationale
- JEP 261: Module System — Official JEP covering JPMS design and require/exports semantics
- Java Language Specification, Chapter 7 (Java SE 25) — Current package and module rules
- Oracle JDK 25 migration guide — Strong encapsulation and
--add-opens - Baeldung: Java 9 Module System — Migration guide from classpath to modules
Conclusion
The Java 9 Module System adds a layer of structure that was missing from Java for two decades. Used well, it gives you explicit dependencies, enforced encapsulation, and a cleaner architecture. Used poorly, it creates migration headaches and confusing error messages. The key insight is that modules are about declaring intent, not just satisfying the compiler.
On current JDKs, remove obsolete --illegal-access flags and use the JDK migration guide to identify unsupported reflective access. Keep exports focused on the public API, and use targeted opens only for documented reflection needs. Remember that JPMS encapsulation does not sandbox code.
Category
Related Posts
JVM Bytecode Verification: Type Checking and Stack Map Frames
A practical guide to JVM bytecode verification by class-file version, including type inference, StackMapTable frames, VerifyError debugging, and verification limits.
CDS and AppCDS: Class Data Sharing for Faster JVM Startup
Learn how JVM Class Data Sharing works, create an AppCDS archive with Oracle JDK 21, and benchmark startup on your own workload.
JVM in Containers: Cgroup Memory Limits and Heap Sizing
A guide to how the JVM detects container memory limits, configures heap accordingly, and avoids pitfalls when running Java in Docker and Kubernetes.