What is the "default lookup"?
The default lookup is Lookup.getDefault()
.
It is the registry for global singletons and instances of objects which have been registered in the system by modules.
(In JDK 6, ServiceLoader
operates on the same principle.)
The default lookup searches in two places:
-
The META-INF/services/ Lookup contains all objects registered by modules via the Java Extension Mechanism - putting files in the
META-INF/services/
directory of their module JARs (typically done using the @ServiceProvider annotation) -
The contents of the
Services/
folder of the System (configuration) Filesystem (this is harder and somewhat deprecated)
Objects contained in the default lookup are instantiated lazily when first requested. Objects returned by the default lookup may (or may not) be garbage collected if they become unreferenced.
Here is the usual usage pattern:
-
A central "controller" module defines some interface, e.g.
package controller.pkg;
public interface MyService {
void doSomething();
}
-
Each module which wants to implement that service depends on the controller module which defines the interface, and creates and registers an implementation:
@ServiceProvider(service=MyService.class)
public class MyImpl implements MyService {
public void doSomething() {....}
}
It is also possible to declaratively mask other people’s implementations and declaratively order implementations so some will take precedence.
-
The controller finds all implementations and uses them somehow:
for (MyService s : Lookup.getDefault().lookupAll(MyService.class)) {
s.doSomething();
}