JAVA — CHAPTER 21

Java Platform Module System · Concept Cheat Sheet
module-info.java requires / exports Dependency Graphs jlink ServiceLoader
1 WHY MODULES?

The problem before modules

  • Every public class/package was accessible to any other code ("the classpath")
  • No clear declared dependencies between components
  • Whole JRE shipped even if an app used a tiny fraction of it

What the module system adds

  • Explicit, declared dependencies between modules
  • Strong encapsulation — only exported packages are visible outside a module
  • Smaller, custom runtime images (with jlink)
2 MODULE DECLARATIONS
// file: module-info.java module com.example.welcome { requires java.base; // implicit, shown for clarity requires javafx.controls; exports com.example.welcome.api; }

Key directives

DirectiveMeaning
requiresthis module depends on another module
exportsmakes a package visible to other modules
requires transitivedependency is passed along to modules that require this one
opensallows reflective access (e.g. for frameworks) to a package
3 MODULARIZING A WELCOME APP

Turning a plain app into a module is mostly about project layout: put a module-info.java at the source root, keep classes in a package, and declare what the module needs (requires) and shares (exports).

src/ └─ com.example.welcome/ ├─ module-info.java └─ com/example/welcome/Welcome.java
4 MODULE-DEPENDENCY GRAPHS
com.example.app
→ requires →
com.example.utils
→ requires →
java.base

The JVM builds a graph of all module dependencies at startup and verifies it's consistent (no missing or conflicting modules) before your program even starts running — catching configuration errors early.

5 MIGRATING CODE & RESOURCES IN MODULES

Migration strategies

  • Bottom-up — modularize dependencies first, then the app
  • Top-down — modularize the app first, treat old code as an "unnamed module"

Resources

Non-code files (images, config, properties) can live alongside module code and be loaded via Class.getResourceAsStream(), respecting the module's encapsulation rules.

6 CUSTOM RUNTIMES WITH jlink
jlink --module-path $JAVA_HOME/jmods:mods \ --add-modules com.example.welcome \ --output myruntime

Why it matters

jlink creates a minimal, self-contained Java runtime image containing only the modules your app actually needs — much smaller than shipping the full JDK, great for containers and embedded devices.

7 SERVICES & ServiceLoader
// module-info.java (provider module) provides com.example.PaymentService with com.example.impl.CardPaymentService; // consumer code ServiceLoader<PaymentService> loader = ServiceLoader.load(PaymentService.class);

Concept

Modules can declare that they provide an implementation of a service interface, and other modules can discover implementations at runtime via ServiceLoader — a plug-in style architecture built into the platform.