Sub topic 15
Split Packages and How to Fix Them
Assume you know Java packages, access modifiers, module-info.java, and basic javac and java commands. This chapter focuses on one JPMS rule: a package must belong to only one named module.
What is a split package?
A split package is a package whose classes are placed in more than one module. For example, both com.example.orders and com.example.billing contain classes in com.example.shared.
This was possible on the classpath, where the runtime searched jars in order. JPMS rejects it for named modules because lookup becomes ambiguous. The module system must know exactly which module owns each package.
// com.example.orders/module-info.java
module com.example.orders {
exports com.example.shared;
}
// com.example.billing/module-info.java
module com.example.billing {
exports com.example.shared;
}If both modules are resolved together, compilation or startup fails with an error such as package ... exists in another module. Exporting the package does not solve the conflict. exports controls access; it does not change package ownership.
How to fix the conflict
Choose the owner of each package deliberately.
- Consolidate the package. Move all
com.example.sharedclasses into one module, such ascom.example.shared. Other modules declarerequires com.example.shared. - Rename packages by ownership. Use names such as
com.example.orders.sharedandcom.example.billing.sharedwhen the classes are not truly shared. - Separate public API from implementation. Put shared interfaces and value types in an API module. Keep implementation classes in their owning modules.
- Treat the classpath as temporary migration space. A legacy jar can remain outside the named module graph while you migrate it, but do not place duplicate packages in multiple named modules.
A consolidated design might look like this:
// com.example.shared/module-info.java
module com.example.shared {
exports com.example.shared;
}
// com.example.orders/module-info.java
module com.example.orders {
requires com.example.shared;
}
// com.example.billing/module-info.java
module com.example.billing {
requires com.example.shared;
}The shared module owns com.example.shared. The other modules can use exported types without containing another copy of that package.
Finding split packages
Inspect the module path and dependencies before changing code.
java --show-module-resolution \
--module-path mods \
-m com.example.orders/com.example.orders.Main
jdeps --module-path mods --check com.example.ordersAlso inspect each jar's contents. If two modular jars contain the same package, decide whether to merge the classes or rename one package.
Exercise
The orders and billing modules both contain com.example.shared.Validation. What is the cleanest fix if both modules need that class?
Show answer
Move Validation into one shared module, export its package, and add requires for that shared module to both consumers.