Introduction

The module-info.java file is known as the module descriptor.

It defines the structure and configuration of a Java module. It tells Java:

  • The name of the module
  • Which other modules it requires
  • Which packages it exports
  • Which services it uses or provides

A module can have only one module-info.java file.

Basic Structure

A simple module declaration looks like this:

Here, student.module is the name of the module.

The module declaration is written inside the module-info.java file.

requires

The requires keyword is used to declare a dependency on another module.

Here, student.module depends on the java.sql module.

exports

The exports keyword specifies which packages are accessible to other modules.

Here, the student package is exported and can be accessed by other modules that read this module.

Packages that are not exported remain encapsulated.

Example with requires and exports

A module can contain both requires and exports declarations.

This module:

  • Depends on java.sql
  • Makes the student package available to other modules

opens

The opens keyword allows reflective access to a package.

This is useful for frameworks and libraries that need to access classes and members through reflection.

uses

The uses keyword declares that a module uses a particular service.

It is commonly used with Java's Service Provider mechanism.

provides

The provides keyword declares an implementation of a service.

Here, StudentServiceImpl provides an implementation of StudentService.

Complete Example

A module descriptor can contain multiple declarations.

This file describes the module's dependencies, accessible packages, reflective access, and services.

Important Keywords

KeywordPurpose
moduleDeclares a module
requiresDeclares a module dependency
exportsMakes a package available to other modules
opensAllows reflective access to a package
usesDeclares a service used by the module
providesDeclares a service implementation

Key Takeaways

  • module-info.java is the module descriptor.
  • It defines the structure and configuration of a module.
  • requires defines dependencies.
  • exports makes packages accessible to other modules.
  • opens allows reflective access.
  • uses and provides are used for Java's service mechanism.
  • Each module has one module-info.java file.