Creating a Modular JAR with javac and jar
What you'll learn: How to compile a module and package it into a modular JAR file using the standard Java command-line tools.
The Process Overview
A modular JAR is simply a JAR file that contains a module-info.class file at its root. Creating one involves two steps: first compiling your module's source files (including module-info.java), then packaging the compiled classes into a JAR using the jar tool.
Think of it like baking a cake: you first prepare all ingredients (compile), then put them in a proper container (package) so others can enjoy the finished product.
Step-by-Step: Compiling the Module
First, compile your module's source code, including the module descriptor:
javac -d out/production \
src/module-info.java \
src/com/example/myapp/*.java
The -d out/production flag tells javac where to place compiled .class files. The module descriptor (module-info.class) will be placed at the root of this output directory.
Step-by-Step: Creating the Modular JAR
Next, package the compiled classes into a JAR:
jar --create \
--file myapp.jar \
--main-class com.example.myapp.Main \
-C out/production .
The --create flag creates a new JAR, --file specifies the output name, and --main-class (optional) sets the entry point. The -C out/production . changes to the output directory and includes all files.
The resulting myapp.jar contains module-info.class at its root, making it a valid modular JAR that the module system recognizes.
Key Takeaway: Creating a modular JAR requires compiling module-info.java alongside your classes with javac, then packaging everything (including the generated module-info.class) into a JAR using the jar tool—the module descriptor at the JAR root makes it modular.