The 'uses' Directive in module-info.java
What you'll learn: How to declare that your module consumes a service without knowing which implementation will be loaded at runtime.
What Problem Does 'uses' Solve?
Imagine you're writing a logging module. You want to use a logging service, but you don't want to hard-code which specific logger implementation (file logger, console logger, database logger) your module depends on. The uses directive lets you declare: "I need something that implements this service interface, but I don't care what it is until runtime."
This is the consumer side of the Service Provider Interface (SPI) pattern you've already learned about.
The 'uses' Directive Syntax
In your module-info.java, declare your intention to consume a service:
module my.app {
uses com.example.LoggingService;
}
This tells the module system: "This module will look up implementations of LoggingService at runtime using ServiceLoader."
How It Works with ServiceLoader
The uses directive works hand-in-hand with ServiceLoader. At runtime, your code calls:
ServiceLoader<LoggingService> loader = ServiceLoader.load(LoggingService.class);
// Iterate through available implementations
The module system checks your uses declaration to verify you've properly declared your service consumption. Without uses, strong encapsulation rules might prevent service discovery.
Key Characteristics
- Compile-time declaration, runtime binding: You declare the interface you need, but implementations are discovered dynamically
- No direct dependency: You don't
requiresthe provider modules—they can be added or removed without recompiling your consumer module - Multiple implementations:
ServiceLoadercan discover zero, one, or many implementations
Key Takeaway: The uses directive declares that your module consumes a service interface at runtime via ServiceLoader, enabling loose coupling between service consumers and providers without compile-time dependencies on concrete implementations.