Modules

modules1JpmsConcepts

Path
pkg15modules/modules1JpmsConcepts.java
Package
pkg15modules
Study order
1
Run
Single-file source launch
Command
java pkg15modules/modules1JpmsConcepts.java
Lesson
Back to the chapter

There is no in-browser runner. This is the file from the curriculum, unchanged.

pkg15modules/modules1JpmsConcepts.java
1package pkg15modules;2 3/*4 * modules1JpmsConcepts.java5 * -------------------------6 * Java Platform Module System (JPMS) — concepts and vocabulary (Java 9+).7 *8 * DEFINITION:9 *   JPMS (Project Jigsaw) groups code into modules with explicit dependencies.10 *   A module declares what it exports (API) and what it requires (dependencies).11 *   Strong encapsulation: code not exported is inaccessible even via reflection.12 *13 * KEY POINTS:14 *   - module-info.java at the root of a module defines name, requires, exports, provides/uses.15 *   - Classpath apps (no module-info) run in the "unnamed module".16 *   - Automatic modules: a plain JAR on the module path becomes an automatic module.17 *   - Services: provides X with Y + uses X + ServiceLoader (see modules2).18 *19 * Run a real modular demo: see pkg15modules/jpms-demo/ (Maven multi-module).20 */21public class modules1JpmsConcepts {22 23    public static void main(String[] args) {24        Module thisModule = modules1JpmsConcepts.class.getModule();25        System.out.println("This class's module : " + thisModule.getName());26        System.out.println("Is named module?    : " + thisModule.isNamed());27        System.out.println("Can read java.base? : " + thisModule.canRead(ModuleLayer.boot().findModule("java.base").orElseThrow()));28 29        System.out.println("\nmodule-info.java skeleton:");30        System.out.println("""31              module com.myapp {32                  requires java.sql;           // dependency33                  requires transitive java.logging; // re-export to consumers34                  exports com.myapp.api;       // public API package35                  opens com.myapp.internal;    // deep reflection allowed36                  provides com.myapp.spi.Plugin with com.myapp.impl.PluginImpl;37                  uses com.myapp.spi.Plugin;38              }""");39 40        System.out.println("\nClasspath vs Module path:");41        System.out.println("  --class-path   : unnamed module, all jars visible (legacy)");42        System.out.println("  --module-path  : named modules, strong encapsulation");43        System.out.println("  java --module-path mods --module com.myapp/com.myapp.Main");44    }45}