Load in the Java Module System
In the Java Module System, the concept of "load" is primarily associated with the ServiceLoader class, which is used to locate and load service providers. This is a crucial part of the service provider framework in Java, allowing for a decoupled architecture where services can be loaded dynamically at runtime.
Creating a ServiceLoader
The ServiceLoader class provides several static load methods to create an instance. The most straightforward method requires a type token, which is an instance of Class<S> for the service you want to load. This is demonstrated in the following code snippet:
ServiceLoader<TheService> loader = ServiceLoader.load(TheService.class);
This line of code creates a ServiceLoader instance for the service type TheService. This is the simplest way to create a ServiceLoader and is sufficient for most use cases.
Iterating Over Service Providers
Once you have a ServiceLoader instance, you can start iterating over the available service providers. This can be done immediately without needing to keep the ServiceLoader instance around, unless you have specific requirements for laziness or caching. The following example demonstrates how to iterate over the providers:
ServiceLoader
.load(TheService.class)
.iterator()
.forEachRemaining(TheService::doTheServiceThing);
In this example, the iterator method is used to iterate over the service providers, and the forEachRemaining method is used to perform an action on each provider. It's worth noting that there is a historical inconsistency between the iterator method, which lists S, and the stream method, which lists Provider<S>. This is because iterator has been part of Java since version 6, while stream and Provider were introduced in Java 9.
Advanced Usage
While the basic load method is sufficient for most scenarios, there are additional overloads available for more complex cases, such as when dealing with multiple class loaders or module layers. However, these are less common and are not covered here. For those interested, the API documentation provides detailed information on these overloads.
FAQ (Frequently asked questions)
How do you create a ServiceLoader in Java?