Apache NetBeans
Apache NetBeans
Latest release

Apache NetBeans 23

Download

If there is more than one of a type in a Lookup, which instance will I get?

As noted in the overview of Lookup, a Lookup can contain more than one instance of a given class; Lookup is often used for singletons, but not exclusively for singletons. For example, in the Projects API, there is a class called ProjectFactory that recognizes different types of user projects on disk; each module that provides a project type registers another factory in the system.

So the inevitable question is, if there are two instances of X in a Lookup, and I call lookup(X.class), which one do I get?

The answer is, it’s undefined - don’t do that. The next inevitable question is, but how can that be?

A Lookup makes no assumptions about what’s in it, or what you might want to put in it, or how many of anything there should be. That contract is an agreement between whoever tells you that you should get an instance of X from some Lookup and you. If they document that there will only be one, use Lookup.lookup(Class). If they document that there can be more than one, use Lookup.lookupAll(Class) and iterate the results.

In practice this is a non-problem - anything you are going to try to find in a Lookup is going to document whether it is supposed to be a singleton or not.