See Also: ServiceLoader Members
A service-provider loader.
A service provider is a factory for creating all known implementations of a particular class or interface S. The known implementations are read from a configuration file in META-INF/services/. The file's name should match the class' binary name (such as java.util.Outer$Inner).
The file format is as follows. The file's character encoding must be UTF-8. Whitespace is ignored, and # is used to begin a comment that continues to the next newline. Lines that are empty after comment removal and whitespace trimming are ignored. Otherwise, each line contains the binary name of one implementation class. Duplicate entries are ignored, but entries are otherwise returned in order (that is, the file is treated as an ordered set).
Given these classes:
java Example
package a.b.c; public interface MyService { ... } public class MyImpl1 implements MyService { ... } public class MyImpl2 implements MyService { ... }
java Example
# Known MyService providers. a.b.c.MyImpl1 # The original implementation for handling "bar"s. a.b.c.MyImpl2 # A later implementation for "foo"s.
java Example
for (MyService service : ServiceLoader.load(MyService.class)) { if (service.supports(o)) { return service.handle(o); } }
Note that each iteration creates new instances of the various service implementations, so any heavily-used code will likely want to cache the known implementations itself and reuse them. Note also that the candidate classes are instantiated lazily as you call next on the iterator: construction of the iterator itself does not instantiate any of the providers.