CKTIS / Java
to — making a package available to selected modules
In Java SE 21, `to` is a contextual keyword used in `exports` and `opens` directives. It identifies the modules to which the declaring module makes a particular package available.
Version: Java SE 21; repository runtime, production runtime not attested
Syntax
exports PackageName to ModuleName {, ModuleName};
opens PackageName to ModuleName {, ModuleName};to is a contextual keyword, not a reserved keyword. In a module declaration, normally in module-info.java, it introduces the target-module list of an exports or opens directive. Outside the relevant context, it can be an identifier, such as a variable name.
exports p to m; makes the accessible public API of package p available to module m at compile time and run time; normal access rules still apply. opens p to m; enables reflective access by module m, including access to non-public package contents, but does not make the package available for ordinary compile-time use. Without to, the directive does not restrict recipients to a specified list. Names after to identify modules, not packages; separate multiple names with commas.
to does not create a dependency: a module using exported API still needs the appropriate readability relationship, supplied in the example by requires demo.lib;. Repeating a module name within one to clause is a compile-time error. An opens directive cannot appear inside an open module. In the example, demo.api is exported only to demo.app.
Examples
// src/demo.lib/module-info.java
module demo.lib {
exports demo.api to demo.app;
}
// src/demo.lib/demo/api/Message.java
package demo.api;
public class Message {
public static String text() {
return "Hello";
}
}
// src/demo.app/module-info.java
module demo.app {
requires demo.lib;
}
// src/demo.app/demo/app/Main.java
package demo.app;
import demo.api.Message;
public class Main {
public static void main(String[] args) {
System.out.println(Message.text());
}
}Result
Hello
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.