35.1 Using Automatic Modules

Transition from classpath to module path incrementally using automatic modules, while understanding their risks.

What Are Automatic Modules?

A JAR on the module path without module-info.class becomes an automatic module:

  • Module name derived from JAR filename (e.g., commons-lang3-3.12.jarcommons.lang3).
  • Exports all packages.
  • Requires all modules (transitive).

Risks

  • Unstable Naming: Filename changes break dependents.
  • Broad Visibility: No encapsulation; all packages public.
  • Dependency Explosion: requires transitive all modules.

Explicit Module Name (Manifest)

Add Automatic-Module-Name to JAR manifest:

Automatic-Module-Name: org.apache.commons.lang3

Ensures stable name independent of filename.

Migration Strategy

  1. Start with Automatic Modules: Place third-party JARs on module path.
  2. Use Explicit Names: Prefer libraries with Automatic-Module-Name or proper module-info.
  3. Modularize Your Code: Add module-info.java to your modules.
  4. Encourage Library Maintainers: Request proper module descriptors upstream.

Example: Using Automatic Module

// Your module-info.java
module com.example.app {
  requires commons.lang3; // automatic module
  requires java.sql;
}

Detecting Automatic Modules

jar --describe-module --file commons-lang3-3.12.jar

Output shows automatic if no module-info.class.

Guidance

  • Use automatic modules as a bridge, not a destination.
  • Check for Automatic-Module-Name in library manifests.
  • Avoid automatic modules in production if possible; prefer explicit modules.
  • Test migration thoroughly; module resolution differs from classpath.