How can I override an instance in the Default Lookup?

Apache NetBeans Wiki Index

Note: These pages are being reviewed.

As a result of NetBeans design for extensibility, you’ll find a lot of code like this:

DialogDisplayer displayer = DialogDisplayer.getDefault();

in which an API is defined DialogDisplayer as an abstract class or interface and an implementation is indirectly made available through a static method like getDefault(). This approach gives you a default implementation of DialogDisplayer, but also lets you "plug in" a different one of your own design.

How do you do that? First, here’s the implementation of the getDefault() method:

public static DialogDisplayer getDefault() {
    DialogDisplayer dd = (DialogDisplayer) Lookup.getDefault().lookup(DialogDisplayer.class);

    if (dd == null) {
        dd = new Trivial();

    return dd;

As you see, it will attempt to find some instance of DialogDisplayer from the default Lookup (in other words, one that has been registered via META-INF/services/). If it cannot find one, it will return the default implementation (an instance of Trivial, which is an inner class of DialogDisplayer).

Therefore, it seems that you could override the default simply by registering your own implementation of DialogDisplayer). If you tried it, you’d find it doesn’t work (or at least may not work consistently) because there are already other instances registered and they’ll likely take precedence over yours.

So, how do you mask out any other implementations so that yours will be used? In the file where you register the new implementation (META-INF/services/org.openide.DialogDisplayer in this case), you will prefix the other implementation with a pound sign and a minus sign before listing your own on a different line. For example, here’s what the file should look like:

More information about this and other Lookup-related topics, including how to set the order of registered services, can be found in the Utilities API documentation.