Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ServiceLoader to find implementations of an interface

Tags:

I tried to use the Java ServiceLoader to find all classes that implement a specific interface like so:

loader = ServiceLoader.load(Operation.class); try {     for (Operation o : loader) {         operations.add(o);     } } catch (ServiceConfigurationError e) {     LOGGER.log(Level.SEVERE, "Uncaught exception", e); } 

Unfortunately, when I run Eclipse in debug mode the ServiceLoader doesn't find any classes. I feel like I'm missing a trivial point...

like image 559
Caroline Avatar asked Apr 24 '12 18:04

Caroline


People also ask

What is ServiceLoader in Java?

A service provider (or just provider) is a class that implements or subclasses the well-known interface or class. A ServiceLoader is an object that locates and loads service providers deployed in the run time environment at a time of an application's choosing.

What is service provider in Java?

From Java documentation: A service is a well-known set of interfaces and (usually abstract) classes. A service provider is a specific implementation of a service. The classes in a provider typically implement the interfaces and subclass the classes defined in the service itself.


1 Answers

ServiceLoader cannot do it.

In order to expose class as a service that can be discovered by ServiceLoader you need to put its name into provider configuration file, as described in Creating Extensible Applications With the Java Platform .

There are no built-in ways find all classes that implement a particular interface. Frameworks that can do something similar use their own classpath scanning solutions (and even with custom classpath scanning it's not easy because .class files only store information about interfaces implemented directly, not transitively).

like image 131
axtavt Avatar answered Oct 29 '22 02:10

axtavt