- Java 9:Building Robust Modular Applications
- Dr. Edward Lavieri Peter Verhas Jason Lee
- 204字
- 2025-04-04 17:08:34
Strong encapsulation
Earlier in this chapter, you read that Java 9's strong encapsulation remedied the monolithic JDK issue. Encapsulation, in Java 9, is driven by the information in the module-info.java file. The information in this file lets Java know what modules are dependent upon others and what each of them exports. This underscores the importance of ensuring our module-info-java files are properly configured. Let's look at an example written with standard Java code, nothing new in Java 9 in the way this was coded:

In the preceding example, the com.three19.irisScan module has an irisScanner package intended for internal use and an irisScanResult class. If the com.three19.access application tries to import and use the irisScanResult class, the following error message will be produced by the Java Compiler:
src/com.three19.access/com/three19/access/Main.java: error: irisScanResult is not accessible because package com.three19.irisScanner.internal is not exported
private irisSanResult scan1 = new irisScanResult();
^
1 error
If for some reason the compiler does not catch this error, although it would be very unlikely, the following runtime error would occur:
Exception in thread "main" java.lang.IllegalAccessError: class com.three19.access.Main (in module: com.three19.access) cannot access class com.three19.irisScanner.internal.irisScanResult (in module: com.three19.irisScan), com.three19.irisScanner.internal is not exported to com.three19.access.
The detailed error messages will make debugging and troubleshooting much easier.