Java Module Services, requires transitive and static, and Module Tools
Finish the Java module system: requires transitive and aggregator modules, requires static, qualified exports and opens, ServiceLoader with uses and provides, then jdeps, jlink custom runtime images and JMOD files, with a complete runnable example.
kvi5hnuCode Sprout team member12 min readOn this page
This last article on the Java Platform Module System covers the remaining parts of a module declaration: two variants of requires, qualified exports and opens, and uses/provides for service loading. It ends with the JDK tools that analyze modules (jdeps), package them into a trimmed-down runtime (jlink) and store platform modules (jmod). A single runnable program at the end shows every one of these features, including jdeps and jlink running on modules built on the fly.
requires transitive
Sometimes it's tedious for users of a module to declare every module they need. Look at java.desktop. It needs java.prefs, java.datatransfer and java.xml. java.prefs is only used internally, but types from the other two show up in the public API, for example:
java.awt.datatransfer.Clipboard java.awt.Toolkit.getSystemClipboard()
java.beans.XMLDecoder(org.xml.sax.InputSource is)
A caller of those methods needs Clipboard and InputSource, but it shouldn't have to know which modules they come from. So java.desktop declares:
module java.desktop {
requires java.prefs;
requires transitive java.datatransfer;
requires transitive java.xml;
...
}
Every module that requires java.desktop now implicitly reads java.datatransfer and java.xml as well. This is called implied readability.
A compelling use of requires transitive is the aggregator module: a module with no packages, only transitive requirements. The JDK's java.se module is one:
module java.se {
requires transitive java.compiler;
requires transitive java.datatransfer;
requires transitive java.desktop;
...
requires transitive java.sql;
requires transitive java.sql.rowset;
requires transitive java.xml;
requires transitive java.xml.crypto;
}
If you don't care about fine-grained dependencies, requires java.se; gives you the entire Java SE platform. You can list such declarations with java --describe-module java.se.
requires static
The uncommon requires static variant declares that a module is required at compile time but optional at run time. There are two use cases:
- Annotations processed at compile time that live in another module, such as checker or code-generation annotations with
CLASSorSOURCEretention. You need them to compile, but nobody needs them at run time. - Optional dependencies: use a class from another module if it's present and fall back to something else otherwise:
try {
new oracle.jdbc.driver.OracleDriver();
...
} catch (NoClassDefFoundError e) {
// do something else
}
There's a detail that trips people up. A requires static module is not resolved automatically, even if it's on the module path. It only joins the module graph if something else requires it normally or you add it as a root with --add-modules. The demo below shows all three situations. A cleaner way to check is ModuleLayer.boot().findModule("name").isPresent(), which avoids catching errors.
Qualified exports and opens
You can narrow exports and opens to a list of named modules. java.base contains:
exports sun.net to
java.net.http,
jdk.naming.dns;
This is a qualified export. The listed modules can access sun.net, and nobody else can. Code in other modules gets a compile error ("package … is not visible") and an IllegalAccessError at run time.
Heavy use of qualified exports is a sign of a poorly cut module structure. They show up naturally when modularizing an existing code base. sun.net lives in java.base because that's where it's mostly used, but a couple of other modules need it too. The platform designers didn't want to grow java.base further or make sun.net public, so they made it visible only to the modules that need it. In a greenfield project you'd design a proper API instead.
opens can be qualified the same way. In the earlier opens article, the package for a reflection-based utility could have been opened just to that one module:
module com.example.places {
requires com.example.util;
opens com.example.places.model to com.example.util;
}
The JDK itself uses qualified exports and opens heavily. java --describe-module java.base lists dozens of qualified exports … to … lines.
Service loading with uses and provides
The ServiceLoader class matches up service interfaces with implementations. The service-provider-interface article covered it for class-path applications. The module system makes it easier and safer.
A service has an interface:
public interface GreeterService {
String greet(String subject);
Locale getLocale();
}
One or more modules provide implementations:
public class FrenchGreeter implements GreeterService {
public String greet(String subject) { return "Bonjour " + subject; }
public Locale getLocale() { return Locale.FRENCH; }
}
The consumer picks among all available implementations using whatever criteria it likes:
ServiceLoader<GreeterService> loader = ServiceLoader.load(GreeterService.class);
GreeterService chosen = null;
for (GreeterService greeter : loader)
if (greeter.getLocale().getLanguage().equals(desiredLanguage))
chosen = greeter;
On the class path, providers are registered with text files in META-INF/services/. On the module path, module declarations do the job instead:
- A provider module declares
provides Interface with Impl1, Impl2;. The interface may come from any module, but the implementation classes must be in this module. They don't have to be in an exported package. Thejdk.security.authmodule, for example,provides javax.security.auth.spi.LoginModule withKrb5LoginModule,UnixLoginModule,JndiLoginModule,KeyStoreLoginModule,LdapLoginModuleandNTLoginModule. - A consumer module declares
uses Interface;. For example,java.basedeclaresuses javax.security.auth.spi.LoginModule;.
When code in the consumer calls ServiceLoader.load(Interface.class), the providers are found and instantiated even though their packages aren't accessible. That's the point: the implementation stays fully encapsulated, and the consumer only ever sees the interface.

Our service module exports only the API package and keeps the implementations in com.example.greetsvc.internal:
module com.example.greetsvc {
exports com.example.greetsvc;
provides com.example.greetsvc.GreeterService with
com.example.greetsvc.internal.FrenchGreeter,
com.example.greetsvc.internal.GermanGreeter;
}
The consumer requires the service module and declares that it uses the interface:
module app {
requires com.example.greetsvc;
uses com.example.greetsvc.GreeterService;
}
The details worth knowing:
- A
usesdeclaration is mandatory for a named module. Without it,ServiceLoader.loadthrowsServiceConfigurationError. - A provider class needs either a public no-argument constructor, or a
public staticmethod namedprovider()that returns the instance. Theprovider()method lets a singleton or a class that doesn't implement the interface itself act as the provider. loader.stream()(Java 9) returnsServiceLoader.Providerobjects.Provider.type()lets you inspect the class without instantiating it, andget()creates the instance only when you choose it.loader.findFirst()returns anOptionalwith the first provider.- Automatic modules count as providers if their JAR has
META-INF/servicesentries.
Compiling and running is the usual module-path routine:
javac -d mods/com.example.greetsvc $(find greetsvc -name '*.java')
javac -p mods -d mods/app $(find app -name '*.java')
java -p mods -m app/com.example.app.Main fr
Tools for working with modules
jdeps: analyze dependencies
jdeps analyzes the dependencies of class files and JARs. Suppose you want to modularize JUnit 4. jdeps -s gives a summary:
jdeps -s junit-4.12.jar hamcrest-core-1.3.jar
hamcrest-core-1.3.jar -> java.base
junit-4.12.jar -> hamcrest-core-1.3.jar
junit-4.12.jar -> java.base
junit-4.12.jar -> java.management
That's the module graph: JUnit needs Hamcrest, java.base and java.management. Without -s, jdeps also maps packages to the packages and modules they need, and -v goes down to class level. Other useful options:
--generate-module-info dirwrites amodule-info.javafor each JAR, as a starting point for modularization.--generate-open-modulewrites anopen moduleinstead.--jdk-internalsflags uses of internal JDK APIs and suggests replacements, which is essential before migrating to a newer Java.--print-module-depsprints a comma-separated module list, ready forjlink --add-modules.-dotoutput dirwrites Graphviz.dotfiles. Thendot -Tpng dir/summary.dot > summary.pngdraws the graph.--multi-release 21analyzes multi-release JARs for a given version, and--ignore-missing-depskeeps going when some dependencies are absent.
jlink: build a custom runtime image
jlink links your modules and only the platform modules they need into a self-contained runtime image that runs without a separately installed Java:
jlink --module-path mods --add-modules app --output image \
--strip-debug --no-header-files --no-man-pages
image/bin/java --list-modules
image/bin/java -m app/com.example.app.Main

The image has bin/java, a lib/modules file containing the linked modules, and conf, legal and release. All modules are packed into lib/modules, a format internal to the JVM. You can peek inside with jimage list, but other tools aren't meant to generate or consume it. A small application linked with just java.base and java.logging gets a runtime of a few dozen megabytes, a fraction of the full JDK. Useful extras:
--launcher name=module/mainclasscreates abin/namescript.--compress zip-6shrinks the image (older releases used--compress=2).jlinkonly accepts explicit modules. Automatic modules and class-path JARs can't be linked, which is another reason libraries should ship a realmodule-info.- An image is for one platform. To ship Windows, macOS and Linux builds, you link once per target JDK. The
jpackagetool (Java 16+) goes further and wraps an image into a native installer (.msi,.dmg,.deb/.rpm), complete with launcher.
jmod: the JDK's module files
The jmods directory of a JDK contains one .jmod file per platform module. There is no rt.jar any more. JMOD files use the ZIP format and, unlike JAR files, can also hold native libraries, commands, header files, configuration files and legal notices. They're only useful for linking, meaning they're input to jlink and can't be put on the module path at run time. The jmod tool creates and inspects them (jmod list, jmod describe). You only need to produce JMOD files yourself when a module must carry native code or other binary files into the image. Since JDK 24, a JDK can be built without jmods (JEP 493), and jlink then links from the run-time image itself.
A complete example
The program below writes three modules into a temporary directory:
com.example.greetsvcprovides the greeting service. It exports the API, gives a qualified export of a utility package toapp, keeps the implementations hidden and declaresrequires transitive java.loggingbecause its interface returns aLogger.com.example.notesis an annotation-only module.appconsumes the service, uses the qualified export, callslogger()without requiringjava.loggingitself, and hasrequires static com.example.notes.
The program compiles everything with the javac tool provider (note the lint warning when the target of a qualified export isn't compiled yet). It then runs app three times without the optional module, once with it merely on the path, and once with --add-modules. Next it prints the service module's descriptor and shows that a module outside the qualified export can't compile. Finally it runs jdeps -s, links an image with jlink and runs the application from that image.
import java.io.*;
import java.lang.module.*;
import java.nio.file.*;
import java.util.*;
import java.util.spi.ToolProvider;
public class Solution {
static Path root;
static void source(String path, String text) throws IOException {
Path p = root.resolve("src").resolve(path);
Files.createDirectories(p.getParent());
Files.writeString(p, text);
}
static String clean(String s) {
return s.replace(root.toUri().toString(), "").replace(root.toString() + File.separator, "")
.replace(root.toString(), "").replace(File.separatorChar, '/');
}
static void tool(String name, String... args) {
var out = new StringWriter();
int rc = ToolProvider.findFirst(name).orElseThrow().run(new PrintWriter(out, true), new PrintWriter(out, true), args);
out.toString().lines().filter(l -> !l.isBlank()).forEach(l -> System.out.println(" " + clean(l)));
if (rc != 0) System.out.println(" " + name + " failed");
}
static void java(String... args) throws IOException, InterruptedException {
var cmd = new ArrayList<String>(List.of(Path.of(System.getProperty("java.home"), "bin", "java").toString()));
cmd.addAll(List.of(args));
System.out.println(" $ java " + clean(String.join(" ", args)).replace(File.pathSeparator, ":"));
Process p = new ProcessBuilder(cmd).directory(root.toFile()).redirectErrorStream(true).start();
new String(p.getInputStream().readAllBytes()).lines()
.filter(l -> !l.strip().startsWith("at ") && !l.isBlank())
.forEach(l -> System.out.println(" " + clean(l)));
p.waitFor();
}
static String p(String rel) { return root.resolve(rel).toString(); }
static String mp(String... rels) { return String.join(File.pathSeparator, Arrays.stream(rels).map(Solution::p).toList()); }
public static void main(String[] args) throws Exception {
root = Files.createTempDirectory("mods");
// 1. A service module: public API, hidden implementations, a transitive requirement
source("greetsvc/module-info.java", """
module com.example.greetsvc {
requires transitive java.logging; // Logger appears in our public API
exports com.example.greetsvc;
exports com.example.greetsvc.util to app; // qualified export
provides com.example.greetsvc.GreeterService with
com.example.greetsvc.internal.FrenchGreeter,
com.example.greetsvc.internal.GermanGreeter;
}
""");
source("greetsvc/com/example/greetsvc/GreeterService.java", """
package com.example.greetsvc;
import java.util.Locale;
import java.util.logging.Logger;
public interface GreeterService {
String greet(String subject);
Locale getLocale();
default Logger logger() { return Logger.getLogger(getClass().getName()); }
}
""");
source("greetsvc/com/example/greetsvc/util/Banner.java", """
package com.example.greetsvc.util;
public class Banner {
public static String frame(String s) { return "[ " + s + " ]"; }
}
""");
source("greetsvc/com/example/greetsvc/internal/FrenchGreeter.java", """
package com.example.greetsvc.internal;
import java.util.Locale;
import com.example.greetsvc.GreeterService;
public class FrenchGreeter implements GreeterService {
public String greet(String subject) { return "Bonjour " + subject; }
public Locale getLocale() { return Locale.FRENCH; }
}
""");
source("greetsvc/com/example/greetsvc/internal/GermanGreeter.java", """
package com.example.greetsvc.internal;
import java.util.Locale;
import com.example.greetsvc.GreeterService;
public class GermanGreeter implements GreeterService {
public String greet(String subject) { return "Hallo " + subject; }
public Locale getLocale() { return Locale.GERMAN; }
public static GermanGreeter provider() { return new GermanGreeter(); }
}
""");
// 2. An annotation module needed only at compile time (requires static)
source("notes/module-info.java", "module com.example.notes {\n exports com.example.notes;\n}\n");
source("notes/com/example/notes/Reviewed.java", """
package com.example.notes;
import java.lang.annotation.*;
@Retention(RetentionPolicy.CLASS)
public @interface Reviewed { String by(); }
""");
// 3. The consuming application
source("app/module-info.java", """
module app {
requires com.example.greetsvc; // java.logging comes along transitively
requires static com.example.notes; // compile time only, optional at run time
uses com.example.greetsvc.GreeterService;
}
""");
source("app/com/example/app/Solution.java", """
package com.example.app;
import java.util.*;
import com.example.greetsvc.GreeterService;
import com.example.greetsvc.util.Banner;
import com.example.notes.Reviewed;
@Reviewed(by = "Ada")
public class Solution {
public static void main(String[] args) {
String lang = args.length > 0 ? args[0] : "de";
ServiceLoader<GreeterService> loader = ServiceLoader.load(GreeterService.class);
loader.stream().map(p -> p.type().getName()).sorted()
.forEach(n -> System.out.println("provider: " + n));
GreeterService chosen = null;
for (GreeterService g : loader)
if (g.getLocale().getLanguage().equals(lang)) chosen = g;
if (chosen == null) System.out.println("No suitable greeter for " + lang);
else {
System.out.println(Banner.frame(chosen.greet("Modular World")));
System.out.println("logger: " + chosen.logger().getName());
System.out.println("implementation exported? " + chosen.getClass().getModule()
.isExported(chosen.getClass().getPackageName()));
}
System.out.println("notes module present: "
+ ModuleLayer.boot().findModule("com.example.notes").isPresent());
}
}
""");
System.out.println("-- compile the three modules --");
tool("javac", "-d", p("mods/com.example.notes"), p("src/notes/module-info.java"),
p("src/notes/com/example/notes/Reviewed.java"));
tool("javac", "-d", p("mods/com.example.greetsvc"),
p("src/greetsvc/module-info.java"),
p("src/greetsvc/com/example/greetsvc/GreeterService.java"),
p("src/greetsvc/com/example/greetsvc/util/Banner.java"),
p("src/greetsvc/com/example/greetsvc/internal/FrenchGreeter.java"),
p("src/greetsvc/com/example/greetsvc/internal/GermanGreeter.java"));
tool("javac", "-p", p("mods"), "-d", p("mods/app"),
p("src/app/module-info.java"), p("src/app/com/example/app/Solution.java"));
System.out.println("-- run: notes module left off the module path --");
Files.createDirectories(root.resolve("run"));
for (String m : List.of("com.example.greetsvc", "app"))
tool("jar", "-c", "-f", p("run/" + m + ".jar"), "-C", p("mods/" + m), ".");
java("-p", p("run"), "-m", "app/com.example.app.Solution", "de");
java("-p", p("run"), "-m", "app/com.example.app.Solution", "fr");
java("-p", p("run"), "-m", "app/com.example.app.Solution", "it");
System.out.println("-- run with the optional module present --");
java("-p", mp("run", "mods/com.example.notes"), "-m", "app/com.example.app.Solution", "de");
java("-p", mp("run", "mods/com.example.notes"), "--add-modules", "com.example.notes",
"-m", "app/com.example.app.Solution", "de");
System.out.println("-- the descriptor of the service module --");
ModuleDescriptor d = ModuleFinder.of(root.resolve("run")).find("com.example.greetsvc").orElseThrow().descriptor();
d.requires().stream().sorted().forEach(r -> System.out.println(" requires " + r.modifiers() + " " + r.name()));
d.exports().stream().sorted().forEach(e -> System.out.println(" exports " + e));
d.provides().forEach(pr -> System.out.println(" provides " + pr.service() + " with " + pr.providers()));
System.out.println("-- a module outside the qualified export --");
source("other/module-info.java", "module other {\n requires com.example.greetsvc;\n}\n");
source("other/com/example/other/Peek.java", """
package com.example.other;
public class Peek {
String s = com.example.greetsvc.util.Banner.frame("hi");
}
""");
tool("javac", "-p", p("run"), "-d", p("mods/other"),
p("src/other/module-info.java"), p("src/other/com/example/other/Peek.java"));
System.out.println("-- jdeps -s --");
tool("jdeps", "-s", "--module-path", p("run"), p("run/app.jar"));
System.out.println("-- jlink a custom runtime image --");
tool("jlink", "--module-path", p("run"), "--add-modules", "app",
"--strip-debug", "--no-header-files", "--no-man-pages", "--output", p("image"));
Process lm = new ProcessBuilder(p("image/bin/java"), "--list-modules").redirectErrorStream(true).start();
new String(lm.getInputStream().readAllBytes()).lines()
.forEach(l -> System.out.println(" " + l.replaceAll("@[0-9][^ ]*", "")));
lm.waitFor();
Process run = new ProcessBuilder(p("image/bin/java"), "-m", "app/com.example.app.Solution", "fr")
.redirectErrorStream(true).start();
new String(run.getInputStream().readAllBytes()).lines().forEach(l -> System.out.println(" image: " + l));
run.waitFor();
long image = size(root.resolve("image/lib/modules"));
long jdk = size(Path.of(System.getProperty("java.home"), "lib", "modules"));
System.out.println(" image modules file smaller than the full JDK's: " + (image < jdk));
try (var files = Files.walk(root)) {
files.sorted(Comparator.reverseOrder()).forEach(f -> f.toFile().delete());
}
}
static long size(Path p) throws IOException { return Files.size(p); }
}
-- compile the three modules --
src/greetsvc/module-info.java:4: warning: [module] module not found: app
exports com.example.greetsvc.util to app; // qualified export
^
1 warning
-- run: notes module left off the module path --
$ java -p run -m app/com.example.app.Solution de
provider: com.example.greetsvc.internal.FrenchGreeter
provider: com.example.greetsvc.internal.GermanGreeter
[ Hallo Modular World ]
logger: com.example.greetsvc.internal.GermanGreeter
implementation exported? false
notes module present: false
$ java -p run -m app/com.example.app.Solution fr
provider: com.example.greetsvc.internal.FrenchGreeter
provider: com.example.greetsvc.internal.GermanGreeter
[ Bonjour Modular World ]
logger: com.example.greetsvc.internal.FrenchGreeter
implementation exported? false
notes module present: false
$ java -p run -m app/com.example.app.Solution it
provider: com.example.greetsvc.internal.FrenchGreeter
provider: com.example.greetsvc.internal.GermanGreeter
No suitable greeter for it
notes module present: false
-- run with the optional module present --
$ java -p run:mods/com.example.notes -m app/com.example.app.Solution de
provider: com.example.greetsvc.internal.FrenchGreeter
provider: com.example.greetsvc.internal.GermanGreeter
[ Hallo Modular World ]
logger: com.example.greetsvc.internal.GermanGreeter
implementation exported? false
notes module present: false
$ java -p run:mods/com.example.notes --add-modules com.example.notes -m app/com.example.app.Solution de
provider: com.example.greetsvc.internal.FrenchGreeter
provider: com.example.greetsvc.internal.GermanGreeter
[ Hallo Modular World ]
logger: com.example.greetsvc.internal.GermanGreeter
implementation exported? false
notes module present: true
-- the descriptor of the service module --
requires [MANDATED] java.base
requires [TRANSITIVE] java.logging
exports com.example.greetsvc
exports com.example.greetsvc.util to [app]
provides com.example.greetsvc.GreeterService with [com.example.greetsvc.internal.FrenchGreeter, com.example.greetsvc.internal.GermanGreeter]
-- a module outside the qualified export --
src/other/com/example/other/Peek.java:3: error: package com.example.greetsvc.util is not visible
String s = com.example.greetsvc.util.Banner.frame("hi");
^
(package com.example.greetsvc.util is declared in module com.example.greetsvc, which does not export it to module other)
1 error
javac failed
-- jdeps -s --
app -> com.example.greetsvc
app -> java.base
app -> java.logging
-- jlink a custom runtime image --
app
com.example.greetsvc
java.base
java.logging
image: provider: com.example.greetsvc.internal.FrenchGreeter
image: provider: com.example.greetsvc.internal.GermanGreeter
image: [ Bonjour Modular World ]
image: logger: com.example.greetsvc.internal.FrenchGreeter
image: implementation exported? false
image: notes module present: false
image modules file smaller than the full JDK's: true
Common questions
When should I use requires transitive?
When types from the other module appear in your exported API, such as parameters, return types, superclasses or exceptions. Users of your module can then call your API without adding their own requires. javac -Xlint:exports warns when you forget.
Why isn't my requires static module available at run time?
A requires static dependency isn't resolved automatically. It's only present if another module requires it normally, or if you add it with --add-modules. Your code should check for it and fall back when it's missing.
Why does ServiceLoader.load find no providers in my module?
Check three things. The consumer module needs a uses declaration, the provider module needs provides Interface with Impl, and the provider module must be on the module path and resolved. With an automatic module, the provider must be listed in META-INF/services.
How small can a jlink image get?
An application that only needs java.base produces an image of a few tens of megabytes, smaller with --compress, --strip-debug and --no-header-files --no-man-pages. Use jdeps --print-module-deps to find the minimal module list.
What is the difference between jlink and jpackage?
jlink builds a custom runtime image: a directory with a trimmed JVM and your modules. jpackage (Java 16) goes one step further and wraps an application and runtime into a native installer or app bundle for one platform.
API and tools reference
| Item | Description |
|---|---|
requires transitive m; | modules that read this module also read m |
requires static m; | m is required at compile time and optional at run time |
exports p to m1, m2; / opens p to m1, m2; | qualified export/open, only to the listed modules |
uses S; / provides S with Impl1, Impl2; | consume or provide a service |
static <S> ServiceLoader<S> load(Class<S> service) | creates a loader for a service |
Stream<ServiceLoader.Provider<S>> stream() | providers; type() without and get() with instantiation |
Optional<S> findFirst() | the first available provider |
Optional<Module> ModuleLayer.boot().findModule(String name) | checks whether an optional module is present |
ModuleDescriptor.requires()/exports()/provides() | the parsed contents of a module-info.class |
jdeps -s, --generate-module-info, --jdk-internals, --print-module-deps | dependency analysis |
jlink --module-path … --add-modules … --output dir | builds a custom runtime image |
jmod list/describe/create, jimage list, jpackage | JMOD files, runtime image contents, native installers |
Summary
requires transitivepasses readability on to clients. Use it for modules whose types appear in your API. Aggregator modules likejava.seconsist only of transitive requirements.requires staticmeans compile-time only. At run time the module is used only if something else resolves it, for example--add-modules.exports … toandopens … tolimit access to named modules. They're useful during modularization but a smell if overused.provides … withanduseswire upServiceLoaderwithoutMETA-INF/services, and the implementations stay encapsulated.jdepsanalyzes dependencies,jlinkbuilds trimmed runtime images,jmodhandles the JDK's link-time module format, andjpackageturns images into installers.
Practice Questions
Module a has requires transitive b, and module c has requires a. Can code in c use public types from b's exported packages?
Yes. Implied readability means c reads b because it reads a, which requires b transitively. Without transitive, c would need its own requires b;.
Your module declares requires static com.example.metrics and the JAR is on the module path, yet ModuleLayer.boot().findModule("com.example.metrics") is empty. Why?
Static dependencies aren't resolved automatically. The module is only in the graph if another module requires it normally or it's added as a root with --add-modules com.example.metrics.
Why can ServiceLoader instantiate com.example.greetsvc.internal.FrenchGreeter even though that package isn't exported?
Because the provider module declares it in provides GreeterService with FrenchGreeter, and the consumer declares uses GreeterService. The module system grants ServiceLoader access to the declared providers. The consumer still can't name or reflect on the class directly.
What does jdeps --print-module-deps app.jar print, and how is it typically used?
A comma-separated list of the modules the JAR depends on, such as java.base,java.logging. Build scripts feed it into jlink --add-modules to create a minimal runtime image.
Can you jlink an application that depends on an automatic module?
No. jlink needs explicit modules with a module-info.class. You need a modular version of the library, or you must add a module-info to it yourself (for example, generated with jdeps --generate-module-info and compiled with javac --patch-module), or you ship the application with a full JDK or class path instead.
Previous: Java Automatic Modules, the Unnamed Module and Migration Flags
Next: Java Keywords Reference: Every Keyword, Contextual Keyword and Literal
Related reading
- Java Automatic Modules, the Unnamed Module and Migration Flags
- Modular JARs and Reflective Access in Java: opens and open modules
- Java Module requires and exports: Dependencies and Exported Packages
- Java Modules Introduction: The Module Concept and a Hello World Module
- Java Bytecode Engineering: Modifying Class Files with ASM and Java Agents

More in Core Java I
Java volatile, Atomics, Deadlocks and ThreadLocal: Safe Sharing Between Threads
Share data between Java threads without bugs: memory visibility and volatile, final fields, AtomicInteger and compareAndSet, LongAdder, lazy holder initialization, safe publication, lock-ordering deadlocks, ThreadLocal, InheritableThreadLocal and ScopedValue.
Java Condition Objects and the synchronized Keyword: await, signalAll, wait and notify
Make threads wait for a condition safely with Condition.await and signalAll, then learn Java's built-in alternative: synchronized methods and blocks, intrinsic locks, wait and notifyAll, choosing lock objects, client-side locking, and the monitor concept.
Java Race Conditions and ReentrantLock: Synchronizing Shared Data
Why unsynchronized threads corrupt shared data, shown step by step with a lost-update race, and how to fix it with ReentrantLock: the lock/try/finally idiom, critical sections, reentrancy and hold counts, tryLock, fair locks, and the mistakes that cause bugs.
Java invokeAll, invokeAny and Fork-Join: Running Groups of Tasks
Coordinate many concurrent tasks in Java: invokeAll to wait for every result, invokeAny to take the first success, timeouts, ExecutorCompletionService for results in completion order, structured concurrency, and the fork-join framework with RecursiveTask, RecursiveAction and work stealing.
Discussion
Sign in to ask a question or share what you learned.