Archive

Posts Tagged ‘annotation’

NetBeans Platform – how to register a class as a provider of multiple services

January 24, 2011 4 comments
In NetBeans Platform, there is an annotation called ‘ServiceProvider‘, which allows you to declare that your class provides a certain service (i.e., implements a given interface).   This ties directly into the previously blogged about topic of Lookups, as the class thus annotated is added to the global, default lookup.  Recall that a lookup is a nice wrapper around a Map<Class<E>, Collection<? extends E>>, and allows modules to decouple themselves from the service they request from the actual concrete implementation that they receive.  (A much more in-depth discussion can be found on the Dev FAQ section on lookups).

The issue I ran into is that the documentation is not very clear how you can register your class as providing more than one service (again, implementing more than one interface).  For instance, say I have two interfaces I want a class to fulfill:

public interface Foo {
    public String getFoo();
}

public interface Bar {
    public String getBar();
}

public class FooBar implements Foo, Bar {
    public String getFoo() { return "foo"; }

    public String getBar() { return "bar"; }
}
Since you cannot annotate a class twice, the naive solution fails:
// This is a mistake; you can't declare two annotations like this
@ServiceProvider(service=Foo.class)
@ServiceProvider(service=Bar.class)
public class FooBar implements Foo, Bar {
The correct solution is to use the ServiceProviders annotation, which allows you to provide a list of @ServiceProvider declarations.
@ServiceProviders(value={
    @ServiceProvider(service=Foo.class),
    @ServiceProvider(service=Bar.class)}
)
Now you can find the FooBar instance via either defined interface.
Advertisements