Sub topic 11
Public Access and Module Exports
A public class is not always available to every Java program. If the class belongs to a Java module, the module also controls which packages other modules can use.
A module is a named group of packages. A package is a group of related Java classes. Modules give a project another way to separate its public features from its internal code.
This chapter assumes you have used packages, public classes, and methods. You will build a small project with two modules and see how a module shares a package.
Why modules add another boundary
Think of a library as a part of a program that offers useful code to other parts. The library may contain:
- Classes that callers should use.
- Classes that help the library work but are not meant for callers.
A class can be public because it needs to be used by another package inside the same module. That does not necessarily mean the class should be available to other modules.
A module can export a package. Exporting means making the package’s public types available to code in other modules that can read it. A type is a Java class, interface, or similar declaration.
A module that wants to use another module usually declares that it requires it. This creates a readability relationship: the requiring module can read the required module.
For ordinary access from one named module to another, all of these conditions matter:
- The caller’s module reads the module that contains the class.
- The other module exports the class’s package to the caller’s module.
- The class and the member being used have suitable Java access, such as public.
Module rules add to Java access rules. They do not replace them. For example, exporting a package does not make a package-private class public.
Describe a module
A named module has a module descriptor: a file called module-info.java that declares the module and its relationships.
Here is a descriptor for a library module:
module com.example.library {
exports com.example.library.api;
}The module is named com.example.library. It exports the package com.example.library.api.
A descriptor for an app that uses the library can say:
module com.example.app {
requires com.example.library;
}The requires statement says that the app depends on the library. A dependency is something a piece of code needs in order to work.
The two statements have different jobs:
| Statement | Written by | Purpose |
|---|---|---|
| exports | The module offering a package | Makes that package available to other modules |
| requires | The module using another module | Declares the dependency and creates readability |
An export names one exact package. Exporting com.example.library.api does not also export com.example.library.api.tools. Despite the similar names, those are separate packages.
Build a two-module example
This example needs a Java Development Kit, or JDK, version 9 or later. The JDK includes javac, the compiler that turns Java source code into class files, and java, the tool that runs them.
Check that both tools are available:
javac --version
java --versionCreate a new working directory for the example. Run the following commands inside it. These commands use a Unix-style shell, such as the one on macOS or Linux.
mkdir -p src/com.example.library/com/example/library/api
mkdir -p src/com.example.library/com/example/library/internal
mkdir -p src/com.example.app/com/example/appThe two directories directly under src are named after the modules. Inside each one, the remaining directories match the package names.
Create the library module
Create src/com.example.library/module-info.java:
module com.example.library {
exports com.example.library.api;
}Create src/com.example.library/com/example/library/api/Greeter.java:
package com.example.library.api;
import com.example.library.internal.MessageFormatter;
public class Greeter {
public String greet(String name) {
return MessageFormatter.greeting(name);
}
}Greeter is the class that the app will use. Its public greet method provides the library’s feature.
The method uses another class to prepare its result. Create that class in src/com.example.library/com/example/library/internal/MessageFormatter.java:
package com.example.library.internal;
public class MessageFormatter {
public static String greeting(String name) {
return "Hello, " + name + "!";
}
}MessageFormatter is public because Greeter is in a different package. Both packages are inside the same module, so Greeter can use the public class even though the internal package is not exported.
The app, however, cannot ordinarily use MessageFormatter directly. The library does not export its package.
Create the app module
Create src/com.example.app/module-info.java:
module com.example.app {
requires com.example.library;
}Now create src/com.example.app/com/example/app/Main.java:
package com.example.app;
import com.example.library.api.Greeter;
public class Main {
public static void main(String[] args) {
Greeter greeter = new Greeter();
System.out.println(greeter.greet("Mina"));
}
}The app imports Greeter from the exported package. The import lets the source file use the short name Greeter. It does not create a module dependency; the requires statement does that.
The app does not need to export its own package for this example. It is the program’s starting point, not a package that the library needs to use.
Compile and run
From the working directory, run:
javac --module-source-path src -d out -m com.example.library,com.example.app
java --module-path out -m com.example.app/com.example.app.MainThe first command compiles the two modules. The module source path tells javac where to find their source directories. The -d option puts the compiled files in out.
The second command runs the app. The module path tells Java where to find compiled modules. After -m, the first name is the module and the second is the class containing the main method.
The output is:
Hello, Mina!The call works because the app requires the library, the library exports the API package, and both Greeter and greet are public.
Test the boundary
The example has two public classes in the library. They do not have the same module-level availability.
| Class | Package exported? | Can the app use it directly? |
|---|---|---|
| Greeter | Yes | Yes, because the app requires the library |
| MessageFormatter | No | No, even though the class is public |
If Main tries to import MessageFormatter, the compiler reports that the internal package is not visible. The exact error text can vary by JDK version.
This boundary lets the library authors change MessageFormatter without promising it as part of the library’s public API. An API, or application programming interface, is the set of features that other code is intended to use.
Remove an export or a requirement
To see why both declarations matter, try each change separately:
- Remove the exports statement from the library descriptor. Compile again. The app can no longer use Greeter because its package is not exported.
- Restore the exports statement. Remove the requires statement from the app descriptor. Compile again. The app no longer declares that it reads the library.
- Restore both statements and compile again.
When you change a module descriptor during experiments, remove the old out directory before compiling again. That way, the run uses newly compiled files rather than leftover output. Only remove the out directory you created for this example.
Export to selected modules
An ordinary exports statement makes a package available to any module that reads the exporting module. Sometimes a library wants to share a package only with a known partner module.
A qualified export names the modules allowed to use the package. In the example, you can replace the library descriptor with this version:
module com.example.library {
exports com.example.library.api to com.example.app;
}Recompile and run the same commands. The app still works because it is named in the export. A different module would not get access to that package through this export, even if it required the library.
A qualified export can be useful for a closely related support module. Use it carefully: adding another allowed module requires changing the library descriptor.
Requirements do not pass on automatically
Suppose an app requires a library, and that library requires a third module. The app does not automatically read the third module just because the library does.
Usually, the app should declare its own requires statement if it directly uses the third module’s types.
There is also a requires transitive statement. A module can use it when it deliberately wants modules that require it to read a dependency too. This can be useful when a library’s public API exposes types from that dependency. It should not be added merely to avoid thinking about which modules an app needs.
Java’s own standard library is organized into modules as well. Every named module reads java.base automatically. Other modules may need an explicit requirement when you use their features.
Exports and opens are different
Java also has reflection, a way for a program or tool to inspect classes while a program is running. Some tools use it to work with members that are not public.
An opens statement gives reflective access to a package. It is different from exports:
- exports is for ordinary access to public types in a package.
- opens is for reflection at run time, including access that may be needed for nonpublic members.
Opening a package does not make it an ordinary exported package for Java source code. Do not add opens when the problem is that another module needs to compile an import of a public class.
Modules and older projects
Before modules were introduced in Java 9, Java projects commonly placed compiled code on the classpath. The classpath is a list of places where Java looks for classes. A project can still use it without writing module descriptors.
Code on the classpath belongs to an unnamed module rather than a named module like the ones in the example. Mixing classpath code with named modules has extra rules. In particular, a named module does not automatically read the unnamed module. Moving files to a module path or adding a descriptor is therefore not always enough to make an older project work unchanged.
For your first modular project, keeping your own modules on the module path, as in the example, makes the relationships easier to follow.
Common problems
When code cannot use a class from another module, check these points in order:
- Check the class and member access. The class and the method you call usually need to be public across packages.
- Check the package name. The library must export the exact package containing the class.
- Check the app descriptor. The app must require the library module.
- Check the module path. The compiler and the Java launcher must be able to find the modules they need.
- Check for old output. Rebuild after changing module descriptors.
Also avoid placing the same package in two modules. That arrangement is called a split package, and it can cause module resolution or compilation errors. Module resolution is the process Java uses to find modules and connect their declared dependencies.
A good starting design is to export only packages that callers need. Keep supporting packages unexported, then add exports when there is a clear reason to make them part of the API.
Exercises
Exercise
The app requires the library, and Greeter is public. Why can the app use Greeter but not the public MessageFormatter?
Show answer
The library exports Greeter’s package, but it does not export MessageFormatter’s internal package.
Exercise
The library exports its API package only to com.example.app. Can another module use that package just by requiring the library?
Show answer
No. The qualified export allows access only to the named module. The other module would need to be included in the export as well.
Exercise
A library exports a package that contains a package-private class. Does the export make the class public to other modules?
Show answer
No. The export makes public types in the package available under the module rules; normal Java access rules still apply.