Java / Java 21 Interview Questions
What is the Java Platform Module System (JPMS) and when should you use it?
JPMS (Project Jigsaw, JEP 261, Java 9) introduces the concept of modules — named, versioned groups of packages with explicit dependency declarations and access control. It solves the classpath hell problem (no visibility into what JARs exist or what they expose) and improves security by allowing packages to be completely non-accessible to other modules.
// module-info.java — at the root of the source tree
module com.example.myapp {
// Explicit dependencies
requires java.sql;
requires com.example.utils;
requires transitive com.example.api; // transitive: callers get it too
requires static com.example.opt; // optional at runtime
// Explicit exports — only these packages are readable by other modules
exports com.example.myapp.api;
exports com.example.myapp.model to com.example.web; // qualified export
// Opens for reflection (e.g., for Spring, Hibernate, Jackson)
opens com.example.myapp.model; // to all modules
opens com.example.myapp.impl to spring.core; // to Spring only
// Service provider / consumer
uses com.example.api.Plugin; // consumes
provides com.example.api.Plugin // provides
with com.example.myapp.impl.MyPlugin;
}
// Compile
// javac --module-source-path src -d out -m com.example.myapp
// Run
// java --module-path out -m com.example.myapp/com.example.myapp.Main
// Reflect without opens in module — use --add-opens at JVM startup
// java --add-opens java.base/java.lang=com.example.myapp ...Practical reality: most enterprise applications still use the unnamed module (plain classpath) because migrating large codebases to named modules is complex, and many libraries do not provide module-info.java yet. However, libraries and frameworks are increasingly module-aware, and applications targeting the JVM directly (command-line tools, serverless jars) benefit greatly from JPMS for smaller deployable images via jlink.
More Related questions...