All 15 Class Loading & Bytecode Verification questions
More in Class Loading & Bytecode Verification
Advertisement
Java › Class Loading & Bytecode Verification

How does the Java Platform Module System (JPMS, introduced in Java 9) change class loading and encapsulation compared to the traditional classpath model?

Intermediate

Answer

Prior to JPMS, all classes on the classpath were effectively globally visible to each other regardless of intended internal package boundaries (a public class in any JAR could be accessed by any other code on the classpath); JPMS introduces explicit module boundaries (declared via module-info.java) where a module must explicitly `exports` a package to make it accessible outside the module, and other modules must explicitly `requires` it to use it -- this provides genuine, JVM-enforced strong encapsulation (not just a documentation convention), preventing reflective access to non-exported internals unless the module explicitly `opens` that package, a significant shift from the classpath model's effectively-everything-is-public default.
// module-info.java
module com.example.myapp {
    requires java.sql;
    exports com.example.myapp.api;      // publicly usable by other modules
    // com.example.myapp.internal is NOT exported -- inaccessible outside this module
}
Real-world example A library author uses JPMS to genuinely hide internal implementation packages from consumers (unlike the classpath era, where marking a package as "internal" was purely a naming convention consumers could ignore), enforced by the JVM itself rejecting any attempt to access or reflectively invoke methods in a non-exported package.

Common follow-ups: What is the difference between exports and opens in a module-info.java file?;How does JPMS handle backward compatibility with libraries still built for the traditional unnamed classpath module?