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. Note that in JDK 6, ServiceLookup operates on the same principle. The default lookup searches in two places:
Objects contained in lookup are instantiated lazily when first requested.
Here is the usual usage pattern:
1. A central "controller" module defines some interface, e.g.
package controller.pkg;
public interface MyService {
void doSomething();
}
2. Each module which wants to implement that service depends on the controller module which defines the interface, and creates an implementation:
public class MyImpl implements MyService { // must be public
public MyImpl() {} // must have public no-arg constructor
public void doSomething() {....}
}
3. The implementing module registers its implementation declaratively - by putting a flat file in its JAR that identifies the interface by class name: module/src/META-INF/services/controller.pkg.MyService and in its content, has one or more lines that name implementation classes
module.pkg.MyImpl
It is also possible to declaratively mask other people's implementations and declaratively order implementations so some will take precedence.
4. The controller finds all implementations and uses them somehow:
| NetBeans 5 Code | NetBeans 6 Code |
|---|---|
| Collection c = Lookup.getDefault().lookup( new Lookup.Template(MyService.class)). allInstances(); for (Iterator i=c.iterator(); i.hasNext();) { MyService s = (MyService) i.next(); s.doSomething(); } | Collection <? extends MyService> c = Lookup.getDefault().lookupAll ( MyService.class); for (MyService s : c) { s.doSomething(); } |
The NetBeans 5 code will work in NetBeans 6 as well, the NetBeans 6 code is just less verbose. For more info on changes in Lookup in NetBeans 6 see Lookup and Generics.