Caroline
Caroline

Reputation: 381

ServiceLoader to find implementations of an interface

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...

Upvotes: 25

Views: 31574

Answers (3)

axtavt
axtavt

Reputation: 242686

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).

Upvotes: 38

Antoniossss
Antoniossss

Reputation: 32507

In order to scan your classpath at runtime for implementations of specific interface you would need to use different solution eg. Reflections (notice s on the end, this is not java's Reflection API)

Upvotes: 3

Xiao
Xiao

Reputation: 1572

If the implementations are ones that you wrote yourself, you could use AutoService to make them available through the ServiceLoader interface, eg

@AutoService(Operation.class)
class Foo implements FooInterface {

}

@AutoService(Operation.class)
class Bar extends Foo {

}

Upvotes: 26

Related Questions