Sub topic 2
Finding Modules and Building a Runtime with `jlink`
This chapter assumes you can compile Java with javac, run it with java, use the command line, and understand JARs and the classpath. You also need a modular application with a module-info.java file.
Finding the modules you need with `jdeps`
jdeps analyzes compiled classes and reports their dependencies. The --print-module-deps option prints the JDK modules needed by a JAR:
jdeps --print-module-deps mods/app.jarFor an application that uses java.util.logging, the output includes:
java.base,java.loggingjava.base is always present because it contains core Java classes. java.logging is an additional dependency. A module descriptor makes this dependency explicit:
module com.example.app {
requires java.logging;
}jdeps is useful as a check, but it does not replace testing. Reflection, dynamically loaded classes, and service providers can create dependencies that static analysis cannot see.
Your first `jlink` image
jlink combines application modules with JDK modules into a runtime image. The module path must contain both the JDK's jmods directory and your application module:
jlink \
--module-path "$JAVA_HOME/jmods:mods" \
--add-modules com.example.app \
--output build/runtimeOn Windows, use ; instead of : in the module path.
The --add-modules option names the root module. jlink follows its requires declarations and adds the required modules.
What is inside the image
A runtime image is a directory, not a single JAR.
| Path | Purpose |
|---|---|
| `bin/` | Java commands and generated launchers |
| `conf/` | Runtime configuration |
| `lib/` | Runtime libraries and module data |
| `release` | Version and build metadata |
Inspect the modules and metadata:
build/runtime/bin/java --list-modules
cat build/runtime/releaseAdding a launcher
Create a named command with --launcher:
jlink \
--module-path "$JAVA_HOME/jmods:mods" \
--add-modules com.example.app \
--launcher hello=com.example.app/com.example.app.Main \
--output build/runtimeRun it with:
build/runtime/bin/helloExercise
Why does jlink need the application module's requires declarations?
Show answer
They form the dependency graph jlink follows to include the modules required at runtime.