Converting a Non-Modular JAR to a Modular JAR
You'll learn how to transform an existing non-modular JAR into a fully modular JAR by adding a module descriptor and properly declaring its boundaries.
The Conversion Process
Converting a non-modular JAR to a modular one means taking a library that was built without JPMS in mind and giving it a formal module identity. This involves creating a module-info.java file, declaring what other modules it needs, and explicitly stating which packages it makes available to the outside world.
Think of it like turning a house without blueprints into one with architectural plans—you're documenting what was already there implicitly and making those boundaries official.
Step-by-Step Conversion
1. Add module-info.java to the source root:
Create a module-info.java file at the root of your source directory (alongside your package folders, not inside them).
2. Declare the module and name it:
module com.mylib.utilities {
}
3. Declare dependencies with requires:
Identify external libraries your JAR uses and add requires directives:
module com.mylib.utilities {
requires java.sql;
requires org.apache.commons.lang3;
}
4. Export public packages: Determine which packages contain your public API and export them:
module com.mylib.utilities {
requires java.sql;
requires org.apache.commons.lang3;
exports com.mylib.utilities.core;
exports com.mylib.utilities.helpers;
}
5. Recompile and repackage:
Compile with javac including the module descriptor, then create the JAR with the jar command as usual.
Your internal implementation packages (those not exported) are now strongly encapsulated—other modules can't access them, even if the classes are public.
Key Takeaway: Converting a non-modular JAR to modular requires adding module-info.java, using requires to declare dependencies, and exports to explicitly expose only your public API packages—transforming implicit structure into enforced boundaries.