Martin Pernollet
Martin Pernollet

Reputation: 2315

Netbeans Lookup: defining ServiceProvider with annotations and not via text/xml files

I need to have the simplest possible way of providing an implementation of an interface via an external jar. I want to avoid using text/xml files as it can cause errors when class or interface names are refactored.

I tried Netbeans Lookup, since it has a @ServiceProvider annotation supposed to register the implementation in a declarative way.

So I wrote a simple trial code which does not even split interface and provider in different jars, but it still fail to lookup components:

import org.openide.util.Lookup;
import org.openide.util.lookup.ServiceProvider;

public class LookupTrial {
public static void main(String[] args) {
    IService s = Lookup.getDefault().lookup(IService.class);
    if(s==null)
        throw new RuntimeException("lookup failed");
    else
        s.hello();
}

public interface IService{
    public void hello();
}

@ServiceProvider(service=IService.class)
public class MyImplementation implements IService{
    public MyImplementation(){}

    @Override
    public void hello() {
        System.out.println("hello lookup");
    }
}
}

Am I wrongly using Lookup? Should I search another Lookup library to do what I want?

Upvotes: 5

Views: 2144

Answers (1)

dajood
dajood

Reputation: 4050

I found the solution. The @ServiceProviderannotation is parsed somehow by the Netbeans IDE and creates a file structure which represents the mapping for the services and their implementation. If you're working without an IDE that is capable to do that (i guess only NB does it), you'll propably have to create those files manually and the annotation won't work. I'd be glad if someone proves me wrong, especially for Intellij IDEA.

For informations on creating the file structure to use Lookup, see here

Another way for you to make use of the Lookup API outside of a Netbeans Platform application may be the AbstractLookup and InstanceContent classes. Have a look here on how to use them.

Upvotes: 2

Related Questions