user5182503
user5182503

Reputation:

Is it possible to get service by module name in Java 9?

Lets consider the situatiton - there are N modules and all of them have the service of the same interface (com.foo.SomeService). Is it possible to get this service by module name (my.module) without iterating all services of all modules?

Upvotes: 2

Views: 140

Answers (2)

Naman
Naman

Reputation: 31968

The ModuleDescriptor.Provides can provide the name of the service provided by the Module.

Module module; // representation for your 'my.module'
Set<ModuleDescriptor.Provides> provides = module.getDescriptor().provides();
provides.forEach(p -> {
    System.out.println("service - " + p.service());
    System.out.println("providers - " + p.providers());
});

Where for e.g. if the module declaration is as follows :

module my.module {
    ...
    provides java.lang.reflect.AnnotatedElement with AnnotateElemenImpl; 
}

where AnnotateElemenImpl class provides the implemenation of an interface AnnotatedElement from java.lang.reflect module. The above shared code segment would return details as :

service - java.lang.reflect.AnnotatedElement
providers - [com.module.AnnotateElemenImpl]

Upvotes: 1

Alan Bateman
Alan Bateman

Reputation: 5449

I can't tell if this is a real question or not. The right way to select a service provider is by probing its capabilities, meaning design a good service interface so that consumers have enough to select an appropriate implementation.

If this question is about configuring something to use a specific service provider then it is not difficult to select by module name if you really need to:

ServiceLoader.load(service).stream()
        .filter(p -> "X".equals(p.type().getModule().getName()))
        .map(Provider::get)
        .findAny();

Upvotes: 2

Related Questions