Add jpms-basics module: JPMS for working developers, exports vs opens, split packages, automatic modules, jdeps and jlink on JDK 25

Five modules built with plain javac/java/jdeps/jlink on Temurin 25.0.5.1. Sources, broken/ cases,
run.sh and captured transcripts in output/. README row added.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_017ic4b4XrpfdpsacrvqnrBM
This commit is contained in:
asmhatre
2026-11-26 20:53:17 +05:30
co-authored by Claude Sonnet 5.5
parent 1fb1455734
commit de2660e998
51 changed files with 953 additions and 0 deletions
+1
View File
@@ -76,6 +76,7 @@ These modules keep only sources, a `run.sh` and their transcripts (`output/`). T
| [`classfile-api/`](classfile-api) | The Java ClassFile API (JEP 484): Read, Generate and Transform Bytecode Without ASM | `java.lang.classfile` final since JDK 24: `parse` and `ClassModel` traversal, `ClassFile.build` with `defineClass` and `defineHiddenClass`, five deliberately broken classes (including swapped exception-table labels that `verify()` misses), timing inserted with `ClassTransform`/`MethodTransform`/`CodeTransform`, the same three jobs in ASM 9.11.1 asserted equal, class-file version limits, a JDK 24/25/26 API diff and a look inside `spring-core` 7.0.10 | | [`classfile-api/`](classfile-api) | The Java ClassFile API (JEP 484): Read, Generate and Transform Bytecode Without ASM | `java.lang.classfile` final since JDK 24: `parse` and `ClassModel` traversal, `ClassFile.build` with `defineClass` and `defineHiddenClass`, five deliberately broken classes (including swapped exception-table labels that `verify()` misses), timing inserted with `ClassTransform`/`MethodTransform`/`CodeTransform`, the same three jobs in ASM 9.11.1 asserted equal, class-file version limits, a JDK 24/25/26 API diff and a look inside `spring-core` 7.0.10 |
| [`jextract/`](jextract) | Calling C from Java with jextract and the FFM API: A Real Library, No JNI | jextract (early-access build for JDK 25) bindings for SQLite 3.45.1, the four arena kinds used wrongly on purpose, `C_POINTER` vs `ADDRESS` (zero-length pointers, and a `SIGSEGV` from `getString` on a NULL pointer), `sqlite3_open` out-parameter, return codes to exceptions, a `sqlite3_exec` upcall (and the JVM exit when it throws), the JDK 25 native-access warning and `--illegal-native-access=deny`, and a JMH comparison of FFM, hand-written JNI and plain Java | | [`jextract/`](jextract) | Calling C from Java with jextract and the FFM API: A Real Library, No JNI | jextract (early-access build for JDK 25) bindings for SQLite 3.45.1, the four arena kinds used wrongly on purpose, `C_POINTER` vs `ADDRESS` (zero-length pointers, and a `SIGSEGV` from `getString` on a NULL pointer), `sqlite3_open` out-parameter, return codes to exceptions, a `sqlite3_exec` upcall (and the JVM exit when it throws), the JDK 25 native-access warning and `--illegal-native-access=deny`, and a JMH comparison of FFM, hand-written JNI and plain Java |
| [`unsafe-migration/`](unsafe-migration) | sun.misc.Unsafe Memory Access Is Going Away: Find and Fix It in Your Dependencies (JEP 471 / 498) | what `--sun-misc-unsafe-memory-access` allow/warn/debug/deny do on JDK 25 (and 21, 26, 27), `javac` removal warnings, jdeps and a bytecode scan of 17 real jars, Netty and Guava at run time, a CAS field to `VarHandle`, an off-heap array to `MemorySegment`, a before/after equivalence check | | [`unsafe-migration/`](unsafe-migration) | sun.misc.Unsafe Memory Access Is Going Away: Find and Fix It in Your Dependencies (JEP 471 / 498) | what `--sun-misc-unsafe-memory-access` allow/warn/debug/deny do on JDK 25 (and 21, 26, 27), `javac` removal warnings, jdeps and a bytecode scan of 17 real jars, Netty and Guava at run time, a CAS field to `VarHandle`, an off-heap array to `MemorySegment`, a before/after equivalence check |
| [`jpms-basics/`](jpms-basics) | Java Modules (JPMS) for Working Developers: module-info, exports, opens and jdeps | five modules built with plain `javac`/`java` on JDK 25: `exports` vs `opens` and the exact `InaccessibleObjectException` text, why `requires transitive` exists, services and `jlink --bind-services` (5 modules vs 49), split packages, automatic modules, the class path as the unnamed module, `jdeps --check/--jdk-internals/--generate-module-info`, and `jlink` image sizes |
## Captured output (`docs/output/`) ## Captured output (`docs/output/`)
+42
View File
@@ -0,0 +1,42 @@
# jpms-basics
Companion code for the ankurm.com post **Java Modules (JPMS) for Working Developers: module-info, exports, opens and jdeps**
(<https://ankurm.com/java-modules-jpms-module-info-exports-opens-jdeps/>). Plain `javac`, `java`, `jdeps`, `jlink`: no Maven, no Gradle.
The explanation lives in the article (collapsible sections); this folder has the sources, `run.sh` and the captured transcripts in `output/`.
## Tested against
| Thing | Version |
|---|---|
| JDK | Eclipse Temurin 25.0.5.1+2 (JDK 25, LTS, GA 2025-09-16), `output/00-versions.txt` |
| jlink input | the matching Temurin 25.0.5.1+2 `jmods` download (the main Temurin 25 tarball has no `jmods/`, see `output/11b-jlink-without-jmods.txt`) |
## Run it
```bash
export PATH=/path/to/jdk-25/bin:$PATH
export JMODS=/path/to/jdk-25-jmods # only for the jlink step; defaults to $JAVA_HOME/jmods
./run.sh # about 2 minutes; rebuilds build/ and regenerates every file in output/
```
Single scenarios once `run.sh` has built `build/mods`:
```bash
java -p build/mods -m com.acme.app/com.acme.app.Main hello
java -p build/mods -m com.acme.app/com.acme.app.Main reflect-private # InaccessibleObjectException
java --add-opens com.acme.greeter/com.acme.greeter.api=com.acme.app -p build/mods -m com.acme.app/com.acme.app.Main reflect-private
```
## Layout
| Path | What |
|---|---|
| `src/com.acme.model`, `.greeter`, `.formal`, `.mapper`, `.app` | five modules: a record, a library with a hidden package and a service, a provider, a tiny reflective mapper, the app (`Main` has one scenario per argument) |
| `broken/` | sources that must fail: unexported package, missing `requires`, non-transitive `requires`, cycle, split package, empty `exports` |
| `legacy/`, `automatic/` | a pre-module jar (no `module-info`) that names `sun.misc.Unsafe`, and a module that requires it as an automatic module |
| `output/` | captured output, one file per topic (`01` build, `02` describe, `03` compile errors, `04` reflection, `05` opens for frameworks, `06` split packages, `07` class path, `08` services, `09` automatic modules, `10` jdeps, `11` jlink) |
## Notes on the transcripts
Absolute paths are rewritten to `file:///.../jpms-basics/` and the unnamed-module hash to `@<hash>`. The jlink image sizes in `11-jlink.txt` are machine dependent; everything else is byte-stable.
MIT licensed, see the repository `LICENSE`.
@@ -0,0 +1,16 @@
package com.acme.autoapp;
import com.legacy.lib.Util;
public class Main {
public static void main(String[] args) {
System.out.println(Util.shout("legacy"));
Module lib = Util.class.getModule();
Module me = Main.class.getModule();
System.out.println(lib + " automatic=" + lib.getDescriptor().isAutomatic());
System.out.println("descriptor exports = " + lib.getDescriptor().exports());
System.out.println("isExported(com.legacy.lib) = " + lib.isExported("com.legacy.lib")
+ ", isOpen = " + lib.isOpen("com.legacy.lib"));
System.out.println("legacy.lib reads " + me.getName() + " = " + lib.canRead(me));
}
}
+3
View File
@@ -0,0 +1,3 @@
module com.acme.autoapp {
requires legacy.lib; // the name the module system derived from legacy-lib-1.2.jar
}
@@ -0,0 +1,9 @@
package com.acme.badinternal;
import com.acme.greeter.internal.Secrets; // public class, but the package is not exported
public class Main {
public static void main(String[] args) {
System.out.println(Secrets.token());
}
}
@@ -0,0 +1,3 @@
module com.acme.badinternal {
requires com.acme.greeter;
}
@@ -0,0 +1,9 @@
package com.acme.badnoreq;
import com.acme.greeter.api.Greeter;
public class Main {
public static void main(String[] args) {
System.out.println(new Greeter().greet("x"));
}
}
@@ -0,0 +1,3 @@
module com.acme.badnoreq {
// forgot: requires com.acme.greeter;
}
@@ -0,0 +1,10 @@
package com.acme.badtransitive;
import com.acme.greeter.api.Greeter;
public class Main {
public static void main(String[] args) {
var g = new Greeter().greet("x"); // returns com.acme.model.Greeting
System.out.println(g.text());
}
}
@@ -0,0 +1,3 @@
module com.acme.badtransitive {
requires com.acme.greeter; // greeter here was built with a plain `requires com.acme.model`
}
@@ -0,0 +1 @@
package cyc.a; public class A { }
@@ -0,0 +1 @@
module cyc.a { requires cyc.b; exports cyc.a; }
@@ -0,0 +1 @@
package cyc.b; public class B { }
@@ -0,0 +1 @@
module cyc.b { requires cyc.a; exports cyc.b; }
@@ -0,0 +1,3 @@
package com.acme.shared;
public class PartA { }
@@ -0,0 +1 @@
module split.a { exports com.acme.shared; }
@@ -0,0 +1,3 @@
package com.acme.shared;
public class PartB { }
@@ -0,0 +1 @@
module split.b { exports com.acme.shared; }
@@ -0,0 +1,11 @@
package com.acme.splitapp;
import com.acme.shared.PartA;
import com.acme.shared.PartB;
public class Main {
public static void main(String[] args) {
System.out.println(PartA.class.getName() + " from " + PartA.class.getModule());
System.out.println(PartB.class.getName() + " from " + PartB.class.getModule());
}
}
@@ -0,0 +1 @@
module splitapp { requires split.a; requires split.b; }
@@ -0,0 +1 @@
package com.acme.bademptyexport; public class Thing { }
@@ -0,0 +1,3 @@
module com.acme.bademptyexport {
exports com.acme.nothing; // typo: the package is com.acme.bademptyexport
}
@@ -0,0 +1,9 @@
package com.legacy.lib;
/** A pre-Java-9 style library: no module-info, and it names a JDK-internal class. */
public class Util {
public static String shout(String s) { return s.toUpperCase() + "!"; }
/** The class literal is enough for jdeps to see the dependency on sun.misc. */
public static String unsafeClassName() { return sun.misc.Unsafe.class.getName(); }
}
+3
View File
@@ -0,0 +1,3 @@
openjdk version "25.0.5.1" 2026-11-17 LTS
OpenJDK Runtime Environment Temurin-25.0.5.1+2 (build 25.0.5.1+2-LTS)
javac 25.0.5.1
+15
View File
@@ -0,0 +1,15 @@
$ javac -d build/mods --module-source-path src --module com.acme.app,com.acme.formal
$ ls build/mods
com.acme.app
com.acme.formal
com.acme.greeter
com.acme.mapper
com.acme.model
$ java --module-path build/mods --module com.acme.app/com.acme.app.Main hello
Greeting[text=Hello, Mumbai! (s3cr3t), formatter=built-in]
$ java -p build/mods -m com.acme.app/com.acme.app.Main hello
Greeting[text=Hello, Mumbai! (s3cr3t), formatter=built-in]
+47
View File
@@ -0,0 +1,47 @@
$ java -p build/mods --describe-module com.acme.greeter
com.acme.greeter file:///.../jpms-basics/build/mods/com.acme.greeter/
exports com.acme.greeter.api
requires com.acme.model transitive
requires java.base mandated
uses com.acme.greeter.api.Formatter
contains com.acme.greeter.internal
$ java -p build/mods --describe-module com.acme.app
com.acme.app file:///.../jpms-basics/build/mods/com.acme.app/
requires java.base mandated
requires com.acme.greeter
requires com.acme.mapper
qualified opens com.acme.app.domain to com.acme.mapper
contains com.acme.app
$ java -p build/mods --describe-module com.acme.formal
com.acme.formal file:///.../jpms-basics/build/mods/com.acme.formal/
requires java.base mandated
requires com.acme.greeter
provides com.acme.greeter.api.Formatter with com.acme.formal.FormalFormatter
contains com.acme.formal
$ java --describe-module java.sql
[email protected]
exports java.sql
exports javax.sql
requires java.base mandated
requires java.transaction.xa transitive
requires java.logging transitive
requires java.xml transitive
uses java.sql.Driver
$ java --list-modules | wc -l
69
$ java -p build/mods -m com.acme.app/com.acme.app.Main inspect
app.isNamed() = true name=com.acme.app
greeter.isNamed() = true
app reads greeter = true
greeter packages = [com.acme.greeter.api, com.acme.greeter.internal]
com.acme.greeter.api exported to app: true opened to app: false
com.acme.greeter.internal exported to app: false opened to app: false
descriptor requires = [mandated java.base (@25.0.5.1), transitive com.acme.model]
descriptor uses = [com.acme.greeter.api.Formatter]
String.class module = module java.base
+47
View File
@@ -0,0 +1,47 @@
$ javac -d build/b1 -p build/mods $(find broken/01-internal-access -name "*.java")
broken/01-internal-access/com/acme/badinternal/Main.java:3: error: package com.acme.greeter.internal is not visible
import com.acme.greeter.internal.Secrets; // public class, but the package is not exported
^
(package com.acme.greeter.internal is declared in module com.acme.greeter, which does not export it)
1 error
[exit code 1]
$ javac -d build/b2 -p build/mods $(find broken/02-no-requires -name "*.java")
broken/02-no-requires/com/acme/badnoreq/Main.java:3: error: package com.acme.greeter.api is not visible
import com.acme.greeter.api.Greeter;
^
(package com.acme.greeter.api is declared in module com.acme.greeter, but module com.acme.badnoreq does not read it)
1 error
[exit code 1]
$ diff src/com.acme.greeter/module-info.java build/src-nt/com.acme.greeter/module-info.java | head -4
3c3
< requires transitive com.acme.model;
---
> requires com.acme.model;
$ javac -d build/b3 -p build/mods-nt $(find broken/03-not-transitive -name "*.java")
broken/03-not-transitive/com/acme/badtransitive/Main.java:8: error: Greeting.text() in package com.acme.model is not accessible
System.out.println(g.text());
^
(package com.acme.model is declared in module com.acme.model, but module com.acme.badtransitive does not read it)
1 error
[exit code 1]
$ javac -d build/b4 --module-source-path broken/04-cycle --module cyc.a,cyc.b
broken/04-cycle/cyc.b/module-info.java:1: error: cyclic dependence involving cyc.a
module cyc.b { requires cyc.a; exports cyc.b; }
^
broken/04-cycle/cyc.a/module-info.java:1: error: cyclic dependence involving cyc.b
module cyc.a { requires cyc.b; exports cyc.a; }
^
2 errors
[exit code 1]
$ javac -d build/b6 $(find broken/06-empty-export -name "*.java")
broken/06-empty-export/module-info.java:2: error: package is empty or does not exist: com.acme.nothing
exports com.acme.nothing; // typo: the package is com.acme.bademptyexport
^
1 error
[exit code 1]
+51
View File
@@ -0,0 +1,51 @@
$ java -p build/mods -m com.acme.app/com.acme.app.Main reflect-public
invoked public method reflectively: Greeting[text=Hello, reflection! (s3cr3t), formatter=built-in]
$ java -p build/mods -m com.acme.app/com.acme.app.Main reflect-private
found the field: private final java.lang.String com.acme.greeter.api.Greeter.prefix
Exception in thread "main" java.lang.reflect.InaccessibleObjectException: Unable to make field private final java.lang.String com.acme.greeter.api.Greeter.prefix accessible: module com.acme.greeter does not "opens com.acme.greeter.api" to module com.acme.app
at java.base/java.lang.reflect.AccessibleObject.throwInaccessibleObjectException(AccessibleObject.java:353)
at java.base/java.lang.reflect.AccessibleObject.checkCanSetAccessible(AccessibleObject.java:329)
at java.base/java.lang.reflect.AccessibleObject.checkCanSetAccessible(AccessibleObject.java:277)
at java.base/java.lang.reflect.Field.checkCanSetAccessible(Field.java:179)
at java.base/java.lang.reflect.Field.setAccessible(Field.java:173)
at com.acme.app/com.acme.app.Main.reflectPrivate(Main.java:60)
at com.acme.app/com.acme.app.Main.main(Main.java:20)
[exit code 1]
$ java --add-opens com.acme.greeter/com.acme.greeter.api=com.acme.app -p build/mods -m com.acme.app/com.acme.app.Main reflect-private
found the field: private final java.lang.String com.acme.greeter.api.Greeter.prefix
read it: Hello
$ java -p build/mods -m com.acme.app/com.acme.app.Main forname-internal
class loaded: com.acme.greeter.internal.Secrets
calling it...
Exception in thread "main" java.lang.IllegalAccessException: class com.acme.app.Main (in module com.acme.app) cannot access class com.acme.greeter.internal.Secrets (in module com.acme.greeter) because module com.acme.greeter does not export com.acme.greeter.internal to module com.acme.app
at java.base/jdk.internal.reflect.Reflection.newIllegalAccessException(Reflection.java:400)
at java.base/java.lang.reflect.AccessibleObject.checkAccess(AccessibleObject.java:670)
at java.base/java.lang.reflect.Method.invoke(Method.java:556)
at com.acme.app/com.acme.app.Main.fornameInternal(Main.java:77)
at com.acme.app/com.acme.app.Main.main(Main.java:22)
[exit code 1]
$ java --add-exports com.acme.greeter/com.acme.greeter.internal=com.acme.app -p build/mods -m com.acme.app/com.acme.app.Main forname-internal
class loaded: com.acme.greeter.internal.Secrets
calling it...
s3cr3t
$ java -p build/mods -m com.acme.app/com.acme.app.Main jdk-internals
found: private final byte[] java.lang.String.value
Exception in thread "main" java.lang.reflect.InaccessibleObjectException: Unable to make field private final byte[] java.lang.String.value accessible: module java.base does not "opens java.lang" to module com.acme.app
at java.base/java.lang.reflect.AccessibleObject.throwInaccessibleObjectException(AccessibleObject.java:353)
at java.base/java.lang.reflect.AccessibleObject.checkCanSetAccessible(AccessibleObject.java:329)
at java.base/java.lang.reflect.AccessibleObject.checkCanSetAccessible(AccessibleObject.java:277)
at java.base/java.lang.reflect.Field.checkCanSetAccessible(Field.java:179)
at java.base/java.lang.reflect.Field.setAccessible(Field.java:173)
at com.acme.app/com.acme.app.Main.jdkInternals(Main.java:94)
at com.acme.app/com.acme.app.Main.main(Main.java:25)
[exit code 1]
$ java --add-opens java.base/java.lang=com.acme.app -p build/mods -m com.acme.app/com.acme.app.Main jdk-internals
found: private final byte[] java.lang.String.value
value length: 5
@@ -0,0 +1,23 @@
$ java -p build/mods -m com.acme.app/com.acme.app.Main mapper
{name=Asha, loyaltyPoints=120}
$ diff src/com.acme.app/module-info.java build/src-noopens/com.acme.app/module-info.java
6d5
< opens com.acme.app.domain to com.acme.mapper;
[exit code 1]
$ java -p build/mods-noopens -m com.acme.app/com.acme.app.Main mapper
Exception in thread "main" java.lang.reflect.InaccessibleObjectException: Unable to make field private final java.lang.String com.acme.app.domain.Customer.name accessible: module com.acme.app does not "opens com.acme.app.domain" to module com.acme.mapper
at java.base/java.lang.reflect.AccessibleObject.throwInaccessibleObjectException(AccessibleObject.java:353)
at java.base/java.lang.reflect.AccessibleObject.checkCanSetAccessible(AccessibleObject.java:329)
at java.base/java.lang.reflect.AccessibleObject.checkCanSetAccessible(AccessibleObject.java:277)
at java.base/java.lang.reflect.Field.checkCanSetAccessible(Field.java:179)
at java.base/java.lang.reflect.Field.setAccessible(Field.java:173)
at com.acme.mapper/com.acme.mapper.Mapper.toMap(Mapper.java:18)
at com.acme.app/com.acme.app.Main.mapper(Main.java:81)
at com.acme.app/com.acme.app.Main.main(Main.java:23)
[exit code 1]
$ java --add-opens com.acme.app/com.acme.app.domain=com.acme.mapper -p build/mods-noopens -m com.acme.app/com.acme.app.Main mapper
{name=Asha, loyaltyPoints=120}
+21
View File
@@ -0,0 +1,21 @@
$ javac -d build/split-all --module-source-path broken/05-split --module split.a,split.b && echo "split.a and split.b compiled"
split.a and split.b compiled
$ javac -d build/split/splitapp -p build/split $(find broken/05-split/splitapp -name "*.java")
broken/05-split/splitapp/module-info.java:1: error: module splitapp reads package com.acme.shared from both split.a and split.b
module splitapp { requires split.a; requires split.b; }
^
1 error
[exit code 1]
$ java -p build/split --add-modules split.a,split.b -m split.a/com.acme.shared.PartA
Error occurred during initialization of boot layer
java.lang.LayerInstantiationException: Package com.acme.shared in both module split.a and module split.b
[exit code 1]
$ javac -d build/split-cp $(find broken/05-split -name "*.java" ! -name module-info.java)
$ java -cp build/split-cp com.acme.splitapp.Main
com.acme.shared.PartA from unnamed module @<hash>
com.acme.shared.PartB from unnamed module @<hash>
+39
View File
@@ -0,0 +1,39 @@
$ javac -d build/cp-classes $(find build/cp-src -name "*.java")
$ java -cp build/cp-classes com.acme.app.Main inspect
app.isNamed() = false name=null
greeter.isNamed() = false
app reads greeter = true
com.acme.greeter.api exported to app: true opened to app: true
com.acme.greeter.internal exported to app: true opened to app: true
String.class module = module java.base
$ java -cp build/cp-classes com.acme.app.Main reflect-private
found the field: private final java.lang.String com.acme.greeter.api.Greeter.prefix
read it: Hello
$ java -cp build/cp-classes com.acme.app.Main forname-internal
class loaded: com.acme.greeter.internal.Secrets
calling it...
s3cr3t
$ java -cp build/cp-classes com.acme.app.Main services
providers found: 0
Greeting[text=Hello, Asha! (s3cr3t), formatter=built-in]
$ java -cp build/cp-classes com.acme.app.Main jdk-internals
found: private final byte[] java.lang.String.value
Exception in thread "main" java.lang.reflect.InaccessibleObjectException: Unable to make field private final byte[] java.lang.String.value accessible: module java.base does not "opens java.lang" to unnamed module @<hash>
at java.base/java.lang.reflect.AccessibleObject.throwInaccessibleObjectException(AccessibleObject.java:353)
at java.base/java.lang.reflect.AccessibleObject.checkCanSetAccessible(AccessibleObject.java:329)
at java.base/java.lang.reflect.AccessibleObject.checkCanSetAccessible(AccessibleObject.java:277)
at java.base/java.lang.reflect.Field.checkCanSetAccessible(Field.java:179)
at java.base/java.lang.reflect.Field.setAccessible(Field.java:173)
at com.acme.app.Main.jdkInternals(Main.java:94)
at com.acme.app.Main.main(Main.java:25)
[exit code 1]
$ java --add-opens java.base/java.lang=ALL-UNNAMED -cp build/cp-classes com.acme.app.Main jdk-internals
found: private final byte[] java.lang.String.value
value length: 5
+17
View File
@@ -0,0 +1,17 @@
$ java -p build/mods -m com.acme.app/com.acme.app.Main services
providers found: 1
Greeting[text=Good day, Asha., formatter=formal]
$ java -p build/mods --show-module-resolution -m com.acme.app/com.acme.app.Main services | grep -v '^root\|^java\.\|^jdk\.'
com.acme.app requires com.acme.greeter file:///.../jpms-basics/build/mods/com.acme.greeter/
com.acme.app requires com.acme.mapper file:///.../jpms-basics/build/mods/com.acme.mapper/
com.acme.greeter requires com.acme.model file:///.../jpms-basics/build/mods/com.acme.model/
com.acme.greeter binds com.acme.formal file:///.../jpms-basics/build/mods/com.acme.formal/
com.acme.formal requires com.acme.greeter file:///.../jpms-basics/build/mods/com.acme.greeter/
providers found: 1
Greeting[text=Good day, Asha., formatter=formal]
$ java -p build/mods-noformal -m com.acme.app/com.acme.app.Main services
providers found: 0
Greeting[text=Hello, Asha! (s3cr3t), formatter=built-in]
@@ -0,0 +1,33 @@
$ jar --describe-module --file build/libs/legacy-lib-1.2.jar
No module descriptor found. Derived automatic module.
[email protected] automatic
requires java.base mandated
contains com.legacy.lib
$ java -p build/libs --describe-module legacy.lib
[email protected] file:///.../jpms-basics/build/libs/legacy-lib-1.2.jar automatic
requires java.base mandated
contains com.legacy.lib
$ unzip -p build/libs-named/legacy-lib-1.3.jar META-INF/MANIFEST.MF
Manifest-Version: 1.0
Automatic-Module-Name: com.legacy.lib
Created-By: 25.0.5.1 (Eclipse Adoptium)
$ java -p build/libs-named --describe-module com.legacy.lib
[email protected] file:///.../jpms-basics/build/libs-named/legacy-lib-1.3.jar automatic
requires java.base mandated
contains com.legacy.lib
$ javac -d build/autoapp -p build/libs/legacy-lib-1.2.jar $(find automatic -name "*.java")
$ java -p build/autoapp:build/libs/legacy-lib-1.2.jar -m com.acme.autoapp/com.acme.autoapp.Main
LEGACY!
module legacy.lib automatic=true
descriptor exports = []
isExported(com.legacy.lib) = true, isOpen = true
legacy.lib reads com.acme.autoapp = true
@@ -0,0 +1,4 @@
legacy/src/com/legacy/lib/Util.java:8: warning: Unsafe is internal proprietary API and may be removed in a future release
public static String unsafeClassName() { return sun.misc.Unsafe.class.getName(); }
^
1 warning
+63
View File
@@ -0,0 +1,63 @@
$ jdeps --module-path build/mods -summary --module com.acme.app
com.acme.app -> com.acme.greeter
com.acme.app -> com.acme.mapper
com.acme.app -> com.acme.model
com.acme.app -> java.base
$ jdeps --module-path build/mods --module com.acme.greeter
com.acme.greeter
[file:///.../jpms-basics/build/mods/com.acme.greeter/]
requires transitive com.acme.model
requires mandated java.base (@25.0.5.1)
com.acme.greeter -> com.acme.model
com.acme.greeter -> java.base
com.acme.greeter.api -> com.acme.greeter.internal com.acme.greeter
com.acme.greeter.api -> com.acme.model com.acme.model
com.acme.greeter.api -> java.lang java.base
com.acme.greeter.api -> java.lang.invoke java.base
com.acme.greeter.api -> java.util java.base
com.acme.greeter.internal -> java.lang java.base
$ jdeps --module-path build/mods --check com.acme.greeter
com.acme.greeter (file:///.../jpms-basics/build/mods/com.acme.greeter/)
[Module descriptor]
requires transitive com.acme.model;
requires mandated java.base (@25.0.5.1);
[Suggested module descriptor for com.acme.greeter]
requires transitive com.acme.model;
requires mandated java.base;
[Transitive reduced graph for com.acme.greeter]
requires transitive com.acme.model;
requires mandated java.base;
$ jdeps --print-module-deps build/libs/legacy-lib-1.2.jar
java.base,jdk.unsupported
$ jdeps --list-deps build/libs/legacy-lib-1.2.jar
java.base
jdk.unsupported
$ jdeps --jdk-internals build/libs/legacy-lib-1.2.jar
legacy-lib-1.2.jar -> jdk.unsupported
com.legacy.lib.Util -> sun.misc.Unsafe JDK internal API (jdk.unsupported)
Warning: JDK internal APIs are unsupported and private to JDK implementation that are
subject to be removed or changed incompatibly and could break your application.
Please modify your code to eliminate dependence on any JDK internal APIs.
For the most recent update on JDK internal API replacements, please check:
https://wiki.openjdk.org/display/JDK8/Java+Dependency+Analysis+Tool
JDK Internal API Suggested Replacement
---------------- ---------------------
sun.misc.Unsafe See https://openjdk.org/jeps/260
$ jdeps --generate-module-info build/generated build/libs/legacy-lib-1.2.jar && cat build/generated/legacy.lib/module-info.java
writing to build/generated/legacy.lib/module-info.java
module legacy.lib {
requires jdk.unsupported;
exports com.legacy.lib;
}
+62
View File
@@ -0,0 +1,62 @@
$ jlink --module-path build/mods:$JMODS --add-modules com.acme.app --launcher acme=com.acme.app/com.acme.app.Main --strip-debug --no-header-files --no-man-pages --output build/image-plain
$ build/image-plain/bin/java --list-modules
com.acme.app
com.acme.greeter
com.acme.mapper
com.acme.model
[email protected]
$ build/image-plain/bin/acme services
providers found: 0
Greeting[text=Hello, Asha! (s3cr3t), formatter=built-in]
$ jlink --module-path build/mods:$JMODS --add-modules com.acme.app --bind-services --launcher acme=com.acme.app/com.acme.app.Main --strip-debug --no-header-files --no-man-pages --output build/image-bound
$ build/image-bound/bin/java --list-modules | grep acme
com.acme.app
com.acme.formal
com.acme.greeter
com.acme.mapper
com.acme.model
$ build/image-bound/bin/java --list-modules | grep -E "jlink|jdeps|jdk.compiler"
[email protected]
[email protected]
[email protected]
$ echo "modules in image-plain: $(build/image-plain/bin/java --list-modules | wc -l), in image-bound: $(build/image-bound/bin/java --list-modules | wc -l)"
modules in image-plain: 5, in image-bound: 49
$ build/image-bound/bin/acme services
providers found: 1
Greeting[text=Good day, Asha., formatter=formal]
$ jlink --module-path build/mods:$JMODS --add-modules com.acme.app,com.acme.formal --launcher acme=com.acme.app/com.acme.app.Main --strip-debug --no-header-files --no-man-pages --output build/image-explicit
$ build/image-explicit/bin/java --list-modules
com.acme.app
com.acme.formal
com.acme.greeter
com.acme.mapper
com.acme.model
[email protected]
$ build/image-explicit/bin/acme services
providers found: 1
Greeting[text=Good day, Asha., formatter=formal]
$ jlink --module-path build/mods:$JMODS:build/libs --add-modules com.acme.app,legacy.lib --output build/image-auto
Error: automatic module cannot be used with jlink: legacy.lib from file:///.../jpms-basics/build/libs/legacy-lib-1.2.jar
[exit code 1]
$ jlink --module-path build/mods:$JMODS --add-modules com.acme.app --launcher acme=com.acme.app/com.acme.app.Main --strip-debug --no-header-files --no-man-pages --compress zip-9 --output build/image-small
$ echo "sizes in KB (machine dependent)"; du -sk build/image-plain build/image-bound build/image-explicit build/image-small | sed "s#build/##"; echo "$(du -sk "$JDK_HOME" | cut -f1) (full JDK)"
sizes in KB (machine dependent)
56752 image-plain
166088 image-bound
56752 image-explicit
43176 image-small
309944 (full JDK)
@@ -0,0 +1,10 @@
$ ls "$JDK_HOME" | tr '\n' ' '
NOTICE bin conf include legal lib man release
$ jlink --module-path build/mods --add-modules com.acme.app --bind-services --launcher acme=com.acme.app/com.acme.app.Main --strip-debug --no-header-files --no-man-pages --output build/image-nojmods
Error: This JDK does not contain packaged modules and cannot be used to create another image with the jdk.jlink module
[exit code 1]
$ jlink --module-path build/mods --add-modules com.acme.app,com.acme.formal --launcher acme=com.acme.app/com.acme.app.Main --strip-debug --no-header-files --no-man-pages --output build/image-nojmods2 && build/image-nojmods2/bin/acme services
providers found: 1
Greeting[text=Good day, Asha., formatter=formal]
+161
View File
@@ -0,0 +1,161 @@
#!/usr/bin/env bash
# Regenerates every file in output/. Needs a JDK 25 on PATH (javac, java, jar, jdeps, jlink).
# Machine-dependent: the jlink size figures. Everything else is byte-stable.
set -u
unset JAVA_TOOL_OPTIONS _JAVA_OPTIONS
cd "$(dirname "$0")"
OUT=output; B=build
rm -rf "$B" "$OUT"; mkdir -p "$OUT" "$B"
# show <file> <description of command...>: print "$ cmd", run it, append the exit code if non-zero
sh_() { # sh_ <file> <command string> (appends)
local f="$OUT/$1"; shift
echo "\$ $*" >> "$f"
bash -c "$*" 2>&1 | sed -e "s#file://$PWD/#file:///.../jpms-basics/#g" -e 's#unnamed module @[0-9a-f]*#unnamed module @<hash>#' >> "$f"; local rc=${PIPESTATUS[0]}
[ $rc -ne 0 ] && echo "[exit code $rc]" >> "$f"
echo >> "$f"
return 0
}
# jlink needs the jmods; Temurin ships them as a separate download. Override with JMODS=/path/to/jmods
export JDK_HOME="$(dirname "$(dirname "$(readlink -f "$(which java)")")")"
export JMODS="${JMODS:-$JDK_HOME/jmods}"
java -version 2>&1 | head -2 > "$OUT/00-versions.txt"
javac -version >> "$OUT/00-versions.txt" 2>&1
# ---- 01 build and run ------------------------------------------------------------------
F=01-build-and-run.txt; : > "$OUT/$F"
sh_ $F 'javac -d build/mods --module-source-path src --module com.acme.app,com.acme.formal'
sh_ $F 'ls build/mods'
sh_ $F 'java --module-path build/mods --module com.acme.app/com.acme.app.Main hello'
sh_ $F 'java -p build/mods -m com.acme.app/com.acme.app.Main hello'
# ---- 02 describing modules --------------------------------------------------------------
F=02-describe.txt; : > "$OUT/$F"
sh_ $F 'java -p build/mods --describe-module com.acme.greeter'
sh_ $F 'java -p build/mods --describe-module com.acme.app'
sh_ $F 'java -p build/mods --describe-module com.acme.formal'
sh_ $F 'java --describe-module java.sql'
sh_ $F 'java --list-modules | wc -l'
sh_ $F 'java -p build/mods -m com.acme.app/com.acme.app.Main inspect'
# ---- 03 compile-time failures ------------------------------------------------------------
F=03-compile-errors.txt; : > "$OUT/$F"
sh_ $F 'javac -d build/b1 -p build/mods $(find broken/01-internal-access -name "*.java")'
sh_ $F 'javac -d build/b2 -p build/mods $(find broken/02-no-requires -name "*.java")'
# variant of greeter with a non-transitive requires
mkdir -p build/src-nt && cp -r src/com.acme.greeter src/com.acme.model build/src-nt/
sed -i 's/requires transitive com.acme.model;/requires com.acme.model;/' build/src-nt/com.acme.greeter/module-info.java
javac -d build/mods-nt --module-source-path build/src-nt --module com.acme.greeter 2>/dev/null
sh_ $F 'diff src/com.acme.greeter/module-info.java build/src-nt/com.acme.greeter/module-info.java | head -4'
sh_ $F 'javac -d build/b3 -p build/mods-nt $(find broken/03-not-transitive -name "*.java")'
sh_ $F 'javac -d build/b4 --module-source-path broken/04-cycle --module cyc.a,cyc.b'
sh_ $F 'javac -d build/b6 $(find broken/06-empty-export -name "*.java")'
# ---- 04 reflection ---------------------------------------------------------------------
F=04-reflection.txt; : > "$OUT/$F"
RUN='java -p build/mods -m com.acme.app/com.acme.app.Main'
sh_ $F "$RUN reflect-public"
sh_ $F "$RUN reflect-private"
sh_ $F "java --add-opens com.acme.greeter/com.acme.greeter.api=com.acme.app -p build/mods -m com.acme.app/com.acme.app.Main reflect-private"
sh_ $F "$RUN forname-internal"
sh_ $F "java --add-exports com.acme.greeter/com.acme.greeter.internal=com.acme.app -p build/mods -m com.acme.app/com.acme.app.Main forname-internal"
sh_ $F "$RUN jdk-internals"
sh_ $F "java --add-opens java.base/java.lang=com.acme.app -p build/mods -m com.acme.app/com.acme.app.Main jdk-internals"
# ---- 05 a framework that needs opens ----------------------------------------------------
F=05-opens-for-frameworks.txt; : > "$OUT/$F"
sh_ $F "$RUN mapper"
# variant: same app, without the `opens` line
mkdir -p build/src-noopens && cp -r src/* build/src-noopens/
sed -i '/opens com.acme.app.domain/d' build/src-noopens/com.acme.app/module-info.java
sh_ $F 'diff src/com.acme.app/module-info.java build/src-noopens/com.acme.app/module-info.java'
javac -d build/mods-noopens --module-source-path build/src-noopens --module com.acme.app 2>/dev/null
sh_ $F 'java -p build/mods-noopens -m com.acme.app/com.acme.app.Main mapper'
sh_ $F 'java --add-opens com.acme.app/com.acme.app.domain=com.acme.mapper -p build/mods-noopens -m com.acme.app/com.acme.app.Main mapper'
# ---- 06 split packages ---------------------------------------------------------------
F=06-split-packages.txt; : > "$OUT/$F"
# two modules that each hold com.acme.shared compile fine on their own: nobody reads both yet
sh_ $F 'javac -d build/split-all --module-source-path broken/05-split --module split.a,split.b && echo "split.a and split.b compiled"'
mkdir -p build/split
javac -d build/split/split.a $(find broken/05-split/split.a -name '*.java') 2>/dev/null
javac -d build/split/split.b $(find broken/05-split/split.b -name '*.java') 2>/dev/null
# ...the moment one module reads both, javac refuses
sh_ $F 'javac -d build/split/splitapp -p build/split $(find broken/05-split/splitapp -name "*.java")'
# ...and the JVM refuses to even boot if both are resolved into the same class loader
sh_ $F 'java -p build/split --add-modules split.a,split.b -m split.a/com.acme.shared.PartA'
# the same three source trees on the CLASS path just work: the unnamed module owns no packages
sh_ $F 'javac -d build/split-cp $(find broken/05-split -name "*.java" ! -name module-info.java)'
sh_ $F 'java -cp build/split-cp com.acme.splitapp.Main'
# ---- 07 classpath vs module path ----------------------------------------------------------
F=07-classpath.txt; : > "$OUT/$F"
mkdir -p build/cp-src && for m in src/*/; do cp -r "$m"/* build/cp-src/; done; rm -f build/cp-src/module-info.java
sh_ $F 'javac -d build/cp-classes $(find build/cp-src -name "*.java")'
CP='java -cp build/cp-classes com.acme.app.Main'
sh_ $F "$CP inspect"
sh_ $F "$CP reflect-private"
sh_ $F "$CP forname-internal"
sh_ $F "$CP services"
sh_ $F "$CP jdk-internals"
sh_ $F "java --add-opens java.base/java.lang=ALL-UNNAMED -cp build/cp-classes com.acme.app.Main jdk-internals"
# ---- 08 services -------------------------------------------------------------------------
F=08-services.txt; : > "$OUT/$F"
sh_ $F "$RUN services"
sh_ $F "java -p build/mods --show-module-resolution -m com.acme.app/com.acme.app.Main services | grep -v '^root\\|^java\\.\\|^jdk\\.'"
# formal is not a dependency of app; take it off the module path and the provider disappears
mkdir -p build/mods-noformal && cp -r build/mods/* build/mods-noformal/ && rm -rf build/mods-noformal/com.acme.formal
sh_ $F 'java -p build/mods-noformal -m com.acme.app/com.acme.app.Main services'
# ---- 09 automatic modules ----------------------------------------------------------------
F=09-automatic-modules.txt; : > "$OUT/$F"
mkdir -p build/legacy-classes build/libs
javac -Xlint:-options -d build/legacy-classes legacy/src/com/legacy/lib/Util.java 2> build/legacy-javac.txt
cp build/legacy-javac.txt "$OUT/09a-legacy-javac-warnings.txt"
jar --create --file build/libs/legacy-lib-1.2.jar -C build/legacy-classes .
sh_ $F 'jar --describe-module --file build/libs/legacy-lib-1.2.jar'
sh_ $F 'java -p build/libs --describe-module legacy.lib'
printf 'Automatic-Module-Name: com.legacy.lib\n' > build/manifest.txt
mkdir -p build/libs-named
jar --create --file build/libs-named/legacy-lib-1.3.jar --manifest build/manifest.txt -C build/legacy-classes .
sh_ $F 'unzip -p build/libs-named/legacy-lib-1.3.jar META-INF/MANIFEST.MF'
sh_ $F 'java -p build/libs-named --describe-module com.legacy.lib'
sh_ $F 'javac -d build/autoapp -p build/libs/legacy-lib-1.2.jar $(find automatic -name "*.java")'
sh_ $F 'java -p build/autoapp:build/libs/legacy-lib-1.2.jar -m com.acme.autoapp/com.acme.autoapp.Main'
# ---- 10 jdeps ----------------------------------------------------------------------------
F=10-jdeps.txt; : > "$OUT/$F"
sh_ $F 'jdeps --module-path build/mods -summary --module com.acme.app'
sh_ $F 'jdeps --module-path build/mods --module com.acme.greeter'
sh_ $F 'jdeps --module-path build/mods --check com.acme.greeter'
sh_ $F 'jdeps --print-module-deps build/libs/legacy-lib-1.2.jar'
sh_ $F 'jdeps --list-deps build/libs/legacy-lib-1.2.jar'
sh_ $F 'jdeps --jdk-internals build/libs/legacy-lib-1.2.jar'
sh_ $F 'jdeps --generate-module-info build/generated build/libs/legacy-lib-1.2.jar && cat build/generated/legacy.lib/module-info.java'
# ---- 11 jlink ----------------------------------------------------------------------------
F=11-jlink.txt; : > "$OUT/$F"
LAUNCH='--launcher acme=com.acme.app/com.acme.app.Main --strip-debug --no-header-files --no-man-pages'
MP='build/mods:$JMODS'
sh_ $F "jlink --module-path $MP --add-modules com.acme.app $LAUNCH --output build/image-plain"
sh_ $F 'build/image-plain/bin/java --list-modules'
sh_ $F 'build/image-plain/bin/acme services'
sh_ $F "jlink --module-path $MP --add-modules com.acme.app --bind-services $LAUNCH --output build/image-bound"
sh_ $F 'build/image-bound/bin/java --list-modules | grep acme'
sh_ $F 'build/image-bound/bin/java --list-modules | grep -E "jlink|jdeps|jdk.compiler"'
sh_ $F 'echo "modules in image-plain: $(build/image-plain/bin/java --list-modules | wc -l), in image-bound: $(build/image-bound/bin/java --list-modules | wc -l)"'
sh_ $F 'build/image-bound/bin/acme services'
sh_ $F "jlink --module-path $MP --add-modules com.acme.app,com.acme.formal $LAUNCH --output build/image-explicit"
sh_ $F 'build/image-explicit/bin/java --list-modules'
sh_ $F 'build/image-explicit/bin/acme services'
sh_ $F "jlink --module-path $MP:build/libs --add-modules com.acme.app,legacy.lib --output build/image-auto"
sh_ $F "jlink --module-path $MP --add-modules com.acme.app $LAUNCH --compress zip-9 --output build/image-small"
sh_ $F 'echo "sizes in KB (machine dependent)"; du -sk build/image-plain build/image-bound build/image-explicit build/image-small | sed "s#build/##"; echo "$(du -sk "$JDK_HOME" | cut -f1) (full JDK)"'
# the same jlink on a JDK that has no jmods directory: JEP 493 mode
F=11b-jlink-without-jmods.txt; : > "$OUT/$F"
sh_ $F "ls \"\$JDK_HOME\" | tr '\\n' ' '"
sh_ $F "jlink --module-path build/mods --add-modules com.acme.app --bind-services $LAUNCH --output build/image-nojmods"
sh_ $F "jlink --module-path build/mods --add-modules com.acme.app,com.acme.formal $LAUNCH --output build/image-nojmods2 && build/image-nojmods2/bin/acme services"
echo "done"
@@ -0,0 +1,97 @@
package com.acme.app;
import com.acme.app.domain.Customer;
import com.acme.greeter.api.Greeter;
import com.acme.mapper.Mapper;
import com.acme.model.Greeting;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.stream.Collectors;
/** One program, one switch: pick a scenario with the first argument. */
public class Main {
public static void main(String[] args) throws Exception {
String mode = args.length > 0 ? args[0] : "hello";
switch (mode) {
case "hello" -> hello();
case "inspect" -> inspect();
case "reflect-private" -> reflectPrivate();
case "reflect-public" -> reflectPublic();
case "forname-internal" -> fornameInternal();
case "mapper" -> mapper();
case "services" -> services();
case "jdk-internals" -> jdkInternals();
default -> throw new IllegalArgumentException("unknown mode " + mode);
}
}
static void hello() {
Greeting g = new Greeter().greet("Mumbai");
System.out.println(g);
}
static void inspect() {
Module app = Main.class.getModule();
Module greeter = Greeter.class.getModule();
System.out.println("app.isNamed() = " + app.isNamed() + " name=" + app.getName());
System.out.println("greeter.isNamed() = " + greeter.isNamed());
System.out.println("app reads greeter = " + app.canRead(greeter));
if (greeter.isNamed()) {
System.out.println("greeter packages = " + greeter.getPackages().stream().sorted().collect(Collectors.toList()));
}
for (String p : new String[] {"com.acme.greeter.api", "com.acme.greeter.internal"}) {
System.out.printf("%-27s exported to app: %-5s opened to app: %s%n",
p, greeter.isExported(p, app), greeter.isOpen(p, app));
}
if (greeter.isNamed()) { // the unnamed module (class path) has no descriptor
System.out.println("descriptor requires = " + greeter.getDescriptor().requires().stream()
.map(Object::toString).sorted().collect(Collectors.toList()));
System.out.println("descriptor uses = " + greeter.getDescriptor().uses());
}
System.out.println("String.class module = " + String.class.getModule());
}
/** exports is not opens: the public API is usable, the private field is not. */
static void reflectPrivate() throws Exception {
Field f = Greeter.class.getDeclaredField("prefix");
System.out.println("found the field: " + f);
f.setAccessible(true);
System.out.println("read it: " + f.get(new Greeter()));
}
/** Reflection on public members of an exported package needs no `opens`. */
static void reflectPublic() throws Exception {
Method m = Greeter.class.getMethod("greet", String.class);
Object r = m.invoke(new Greeter(), "reflection");
System.out.println("invoked public method reflectively: " + r);
}
/** A public class in a package that is not exported cannot be reached, even by name. */
static void fornameInternal() throws Exception {
Class<?> c = Class.forName("com.acme.greeter.internal.Secrets");
System.out.println("class loaded: " + c.getName());
Method m = c.getMethod("token");
System.out.println("calling it...");
System.out.println(m.invoke(null));
}
static void mapper() throws Exception {
System.out.println(Mapper.toMap(new Customer("Asha", 120)));
}
static void services() {
Greeter g = new Greeter();
System.out.println("providers found: " + g.providerCount());
System.out.println(g.greetFormally("Asha"));
}
/** Deep reflection into java.base: the strongly-encapsulated classic. */
static void jdkInternals() throws Exception {
Field f = String.class.getDeclaredField("value");
System.out.println("found: " + f);
f.setAccessible(true);
System.out.println("value length: " + ((byte[]) f.get("hello")).length);
}
}
@@ -0,0 +1,13 @@
package com.acme.app.domain;
public class Customer {
private final String name;
private final int loyaltyPoints;
public Customer(String name, int loyaltyPoints) {
this.name = name;
this.loyaltyPoints = loyaltyPoints;
}
public String name() { return name; }
}
@@ -0,0 +1,7 @@
module com.acme.app {
requires com.acme.greeter; // model comes along because greeter says `requires transitive`
requires com.acme.mapper;
// Deep reflection into the domain package is allowed for exactly one module.
opens com.acme.app.domain to com.acme.mapper;
}
@@ -0,0 +1,9 @@
package com.acme.formal;
import com.acme.greeter.api.Formatter;
/** Not exported at all: the only way in is ServiceLoader. */
public class FormalFormatter implements Formatter {
public String name() { return "formal"; }
public String format(String who) { return "Good day, " + who + "."; }
}
@@ -0,0 +1,4 @@
module com.acme.formal {
requires com.acme.greeter;
provides com.acme.greeter.api.Formatter with com.acme.formal.FormalFormatter;
}
@@ -0,0 +1,7 @@
package com.acme.greeter.api;
/** Service interface. Providers live in other modules and are found with ServiceLoader. */
public interface Formatter {
String name();
String format(String who);
}
@@ -0,0 +1,31 @@
package com.acme.greeter.api;
import com.acme.greeter.internal.Secrets;
import com.acme.model.Greeting;
import java.util.ServiceLoader;
/** The one public class of the module. Its private field is used by the reflection demos. */
public final class Greeter {
private final String prefix = "Hello";
/** Plain greeting, no services involved. */
public Greeting greet(String who) {
return new Greeting(prefix + ", " + who + "! (" + Secrets.token() + ")", "built-in");
}
/** Uses the first Formatter provider found; falls back to greet() when there is none. */
public Greeting greetFormally(String who) {
for (Formatter f : ServiceLoader.load(Formatter.class)) {
return new Greeting(f.format(who), f.name());
}
return greet(who);
}
public int providerCount() {
int n = 0;
for (Formatter ignored : ServiceLoader.load(Formatter.class)) n++;
return n;
}
}
@@ -0,0 +1,7 @@
package com.acme.greeter.internal;
/** public class, public method -- but in a package the module does not export. */
public final class Secrets {
private Secrets() { }
public static String token() { return "s3cr3t"; }
}
@@ -0,0 +1,13 @@
module com.acme.greeter {
// Greeting is part of Greeter's public signature, so every reader of greeter must also read model.
requires transitive com.acme.model;
// The public surface. Anything not listed here is invisible outside the module,
// even if the class is declared `public`.
exports com.acme.greeter.api;
// com.acme.greeter.internal is deliberately NOT exported.
// We look up implementations of Formatter at run time instead of naming them.
uses com.acme.greeter.api.Formatter;
}
@@ -0,0 +1,23 @@
package com.acme.mapper;
import java.lang.reflect.Field;
import java.util.LinkedHashMap;
import java.util.Map;
/**
* A twenty-line stand-in for Jackson, Hibernate or Spring: it reads every declared field of
* any object it is given, private ones included. That is exactly the kind of code that
* needs `opens` from the module that owns the object.
*/
public final class Mapper {
private Mapper() { }
public static Map<String, Object> toMap(Object o) throws ReflectiveOperationException {
Map<String, Object> m = new LinkedHashMap<>();
for (Field f : o.getClass().getDeclaredFields()) {
f.setAccessible(true); // <- the call that the module system polices
m.put(f.getName(), f.get(o));
}
return m;
}
}
@@ -0,0 +1,3 @@
module com.acme.mapper {
exports com.acme.mapper;
}
@@ -0,0 +1,4 @@
package com.acme.model;
/** A value type that crosses a module boundary: greeter returns it, app reads it. */
public record Greeting(String text, String formatter) { }
@@ -0,0 +1,3 @@
module com.acme.model {
exports com.acme.model;
}