Sub topic 16
Migrating an Existing Application to Java Modules
Assume you know Java packages, access modifiers, JAR files, the classpath, interfaces, and basic reflection. This chapter shows a gradual migration from classpath code to named modules. You can migrate one library at a time instead of changing the whole application in one release.
Start with the Unnamed Module
Code on the classpath belongs to the unnamed module. It has no module-info.java, reads every named module, and exposes its packages broadly. This makes it useful during migration, but it provides little encapsulation.
First, inspect the application and its libraries:
jdeps --print-module-deps --ignore-missing-deps app.jarThe output suggests JDK modules required by the application. It may not identify every dependency when libraries use reflection or dynamic loading, so test the application as well.
A practical migration sequence is:
- Put third-party JAR files on the module path when possible.
- Convert one application or library module.
- Add
requiresandexportsbased on actual use. - Run tests after every conversion.
- Move remaining classpath code later.
Automatic Modules as a Bridge
A JAR without module-info.class becomes an automatic module when placed on the module path. Its module name comes from the JAR manifest or filename. It usually exports all packages and reads every other named module.
This allows a named module to depend on an unchanged library:
module com.example.app {
requires legacy.logging;
exports com.example.app.api;
}The name legacy.logging must match the name reported by:
jar --describe-module --file libs/legacy-logging.jarAutomatic modules are migration aids, not a final design. Their names can change when the JAR filename changes, and their broad exports weaken encapsulation.
Handle Reflection and Split Packages
Strong encapsulation can break frameworks that access non-public members reflectively. Use opens for a package that needs deep reflection:
module com.example.app {
exports com.example.app.api;
opens com.example.app.model to com.example.json;
}Use opens only for the framework that needs it. An unqualified opens grants reflective access to every module.
A split package exists when two modules contain the same package. The module system rejects this arrangement on the module path. Move the classes into one module, or rename one package. Do not solve the problem by mixing parts of the same package across the classpath and module path.
Exercise
A library works on the classpath but fails after being moved to the module path because its package is accessed reflectively. What change should you consider?
Show answer
Add an opens directive for that package, preferably qualified to the specific framework module, and verify that the library does not also need an exported public API.