Java Module Basics
Introduction to Java Modules
Java modules, introduced in Java 9, represent a fundamental shift in Java's approach to managing dependencies and improving encapsulation. They provide a more structured way to organize and control access between different parts of an application.
Core Concepts of Java Modules
What is a Java Module?
A Java module is a named, self-describing collection of code and data. It explicitly declares:
- What code is contained within it
- What external code it depends on
- What code it makes available to other modules
Key Module Characteristics
Characteristic |
Description |
Explicit Dependencies |
Modules must declare their dependencies |
Strong Encapsulation |
Controlled visibility of internal packages |
Improved Performance |
Better runtime optimization |
Module Declaration
A module is defined by a special module-info.java
file located at the root of the module:
module com.example.mymodule {
// Module directives go here
requires java.base; // Implicit requirement
requires java.sql; // Explicit dependency
exports com.example.api; // Packages visible to other modules
exports com.example.services to com.example.client; // Restricted exports
}
Module Types
graph TD
A[Module Types] --> B[Named Modules]
A --> C[Automatic Modules]
A --> D[Unnamed Modules]
B --> B1[Explicitly defined with module-info.java]
C --> C1[Derived from classpath JARs]
D --> D1[Legacy code without module information]
Named Modules
- Explicitly defined with a
module-info.java
- Full control over dependencies and exports
Automatic Modules
- Created from existing JAR files on the classpath
- Automatically given a module name based on the JAR filename
Unnamed Modules
- Represents legacy code or classpath-based applications
- Provides backward compatibility
Benefits of Java Modules
- Better Encapsulation
- Explicit Dependencies
- Improved Security
- Enhanced Performance
- Clearer Code Organization
Practical Example
Here's a simple module structure for a LabEx project:
// module-info.java in src directory
module com.labex.moduleexample {
requires java.base;
requires java.logging;
exports com.labex.core.api;
exports com.labex.core.services;
}
Compilation and Running Modules
On Ubuntu 22.04, compile and run modules using:
## Compile modules
javac -d mods --module-source-path src $(find src -name "*.java")
## Run a specific module
java --module-path mods -m com.labex.moduleexample/com.labex.core.Main
Common Challenges
- Migrating existing projects to modules
- Managing complex dependency graphs
- Balancing encapsulation with flexibility