Modules are used to group packages and tightly control what packages belong to the public API. Contrary to
Jar files, modules explicitly declare which modules they depend on, and what packages they export. The JDK itself has been modularized in
Java 9. For example, the majority of the Java standard library is exported by the module java.base. As of Java 25, modules can themselves be imported, automatically importing all exported packages. This is done using import module. For example, import module java.sql; is equivalent to import java.sql.*; import javax.sql.*; // Remaining indirect exports from java.logging, java.transaction.xa, and java.xml Similarly, import module java.base;, similarly, imports all 54 packages belonging to java.base. package org.wikipedia.examples; import module java.base; /** * Importing module java.base allows us to avoid manually importing most classes * The following classes (outside of java.lang) are used: * - java.text.MessageFormat * - java.util.Date * - java.util.List * - java.util.concurrent.ThreadLocalRandom */ public class Example { public static void main(String[] args) { List colours = List.of("Red", "Orange", "Yellow", "Green", "Blue", "Indigo", "Violet"); IO.println(MessageFormat.format("My favourite colour is {0} and today is {1,date,long}", colours.get(ThreadLocalRandom.current().nextInt(colours.size())), new Date() )); } } Modules use the following
keywords: • exports: used in a module declaration to specify which packages are available to other modules • module: declares a module • open: indicates that all classes in a package are accessible via reflection by other modules • opens: used to open a specific package for reflection to other modules • provides: used to declare that a module provides an implementation of a service interface • requires: used in a module declaration to specify that the module depends on another module • to: used with the opens directive to specify which module is allowed to reflectively access the package • transitive: used with the requires directive to indicate that a module not only requires another module but also makes that module's dependencies available to modules that depend on it • uses: used in a module to declare that the module is using a service (i.e. it will consume a service provided by other modules) • with: used with the provides directive to specify which implementation of a service is provided by the module == Standard modules ==