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...
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.
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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With