Sub topic 6
Strong encapsulation: what public really means now
This chapter assumes you know Java packages and access modifiers, how javac and java run programs, and what a jar and the classpath are. It also assumes basic familiarity with reflection. You should have seen module-info.java with requires and exports.
The old meaning of public
Before Java 9, public meant "visible to every class that can see the package." The package could be seen by any code on the classpath. Library authors had no way to say "this class is public for my own other packages, but not for you." The result was that internal classes, such as sun.misc.Unsafe or the internals of popular libraries, became de facto API. Users depended on them, and the authors could not change them without breaking applications.
Modules add a layer above packages. A type is now accessible only if both of these conditions hold:
- The type's own access modifier allows it (
public, orprotectedfor subclasses). - The module that contains it has exported its package to the module that wants to use it, and that module reads the first one.
That second condition is strong encapsulation. The compiler and the JVM both enforce it.
The accessibility rule in detail
Code in module B can use a type T from module A only when all of the following are true:
- B reads A (B has a
requires A, directly or throughrequires transitive, or A isjava.base). - A exports the package containing
T, either to everyone or in a qualified export naming B. Tispublic, or it is aprotectedmember accessed from a subclass.
If any condition fails, you get an error. A public class in a non-exported package is effectively package-private as far as other modules are concerned.
A worked example
Reuse the greeter module from earlier chapters, and add an internal helper that is public but not exported.
// src/com.example.greeter/module-info.java
module com.example.greeter {
exports com.example.greeter.api;
}// src/com.example.greeter/com/example/greeter/internal/Formatter.java
package com.example.greeter.internal;
public class Formatter {
public static String shout(String text) {
return text.toUpperCase() + "!";
}
}// src/com.example.greeter/com/example/greeter/api/Greeter.java
package com.example.greeter.api;
import com.example.greeter.internal.Formatter;
public class Greeter {
public String greet(String name) {
return Formatter.shout("Hello, " + name);
}
}Greeter can use Formatter because both are in the same module. Module boundaries only apply between modules. Now suppose com.example.app tries to use the internal class:
// src/com.example.app/com/example/app/Main.java
package com.example.app;
import com.example.greeter.internal.Formatter;
public class Main {
public static void main(String[] args) {
System.out.println(Formatter.shout("hi"));
}
}Compiling with javac -d out --module-source-path src -m com.example.app fails with an error similar to:
error: package com.example.greeter.internal is not visible
(package com.example.greeter.internal is declared in module com.example.greeter,
which does not export it)Formatter is public, yet the compiler rejects the import. Remove the import and call only Greeter, and the program compiles and runs.
Compile time and run time
The rule is enforced twice.
- Compile time.
javacreports the error shown above. This is the common case. - Run time. The JVM checks access when a link is resolved and when reflection is used. A class compiled against an older version of a module, or code that reaches in with reflection, fails at run time with
IllegalAccessErrororIllegalAccessException.
Run-time enforcement matters because a jar can change between compile time and deployment. If a newer version of com.example.greeter stops exporting a package, a stale app will fail when it first touches that package, not when it starts.
Reflection is covered too
Before Java 9, setAccessible(true) could open any private member of any class. In a named module it now works only when the target package is open to the caller.
// Inside a named module that does not have access to java.base internals
import java.lang.reflect.Field;
public class Peek {
public static void main(String[] args) throws Exception {
Field f = String.class.getDeclaredField("value");
f.setAccessible(true); // throws InaccessibleObjectException
}
}The call throws java.lang.reflect.InaccessibleObjectException. The message names the package and the module and says the package is not opened to your module. Note that this applies even to public members of non-exported packages and to private members of exported ones. Exporting grants access to public types and members at compile time and run time. Opening grants deep reflective access to all members, private ones included. The opens directive is the subject of a later chapter. Here the point is that exports alone never makes private members reachable.
| Package state | Compile against public types | Reflection on public members | Reflection with `setAccessible` on private members |
|---|---|---|---|
| Not exported, not opened | No | No | No |
| Exported only | Yes | Yes | No |
| Opened only | No | Yes | Yes |
| Exported and opened | Yes | Yes | Yes |
An open module declaration opens all of its packages at run time, but only those it also exports are usable at compile time.
Encapsulation of the JDK itself
The JDK follows the same rules. Packages such as java.lang and java.util are exported by java.base. Internal packages such as sun.security.util or jdk.internal.misc are not. Code that compiled against them on Java 8 stops compiling on a modular JDK.
Java 9 through 15 kept a compatibility mode for classpath code: --illegal-access=permit was the default, and it let reflection into JDK internals work with a warning. Java 16 changed the default to deny, and Java 17 removed the option. On a current JDK, classpath code that reflects into JDK internals fails unless you pass a flag.
# Allow classpath code to use deep reflection on java.lang
java --add-opens java.base/java.lang=ALL-UNNAMED -cp app.jar com.example.Main
# Allow compile-time and run-time access to a non-exported package
java --add-exports java.base/sun.security.util=ALL-UNNAMED -cp app.jar com.example.MainALL-UNNAMED means every class loaded from the classpath. You can name a specific module instead. Treat these flags as a repair for a dependency you cannot yet change. They are not a design tool, and each one is a place where the JDK may change under you.
Some APIs are deliberately kept: sun.misc.Unsafe lives in the jdk.unsupported module, which exports and opens sun.misc so older libraries keep working.
Common mistakes
- Assuming
publicis enough. A public class in a package missing fromexportscannot be used from another module. Check the descriptor first. - Exporting too much. Putting every package in
exportsremoves the benefit. Export only the packages that make up your API, and keep implementation in packages that are not exported. - Exporting an API package that leaks internal types. If a public method returns or accepts a type from a non-exported package, callers can hold the value but cannot name its type. The compiler warns about this with
-Xlint:exports. - Fixing reflection errors with
--add-openspermanently. Preferopensin your own module descriptor, or upgrade the library that needs the access. - Testing only on the classpath. Classpath code lives in the unnamed module, where most encapsulation is not enforced for your own code. Tests that pass on the classpath can hide a missing
exports. Run at least one build on the module path.
Design guidance
Decide package by package. Ask whether a user of the module should depend on it for years. If yes, export it. If it exists only to support the exported packages, leave it out. If another module of your own needs it, use a qualified export rather than a general one. Frameworks that reflect over your classes (for example for dependency injection or serialization) need opens, ideally limited to the packages they read.
Exercise
Module lib contains public class Helper in package lib.util. Its descriptor is module lib { exports lib.api; }. Module app has requires lib; and its code imports lib.util.Helper. What happens, and what are two ways to fix it?
Show answer
Compilation fails with "package lib.util is not visible", because lib does not export lib.util, even though Helper is public. One fix is to add exports lib.util; to lib, which makes the package part of its API. If only app should use it, the better fix is a qualified export: exports lib.util to app;. A third option is to move the needed functionality into an exported package such as lib.api.
Exercise
A module exports com.shop.model but does not open it. A serialization library in another module calls setAccessible(true) on a private field of com.shop.model.Order. What happens, and what change to the descriptor fixes it?
Show answer
The call throws InaccessibleObjectException, because exporting does not grant deep reflection on private members. Adding opens com.shop.model; to the descriptor, or opens com.shop.model to the.library.module; to limit it to one module, allows the access.