Netbeans Search: Defining a ServiceProvider with Annotations rather than Text / Xml Files

I need to have the easiest way to ensure the implementation of the interface through an external bank. I want to avoid using text / xml files, as this can cause errors when refactoring class or interface names.

I tried Netbeans Lookup, since it @ ServiceProvider annotations should register the implementation in a declarative way.

So, I wrote a simple trial code that does not even break the interface and the provider in different banks, but it still can not find the 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 using Lookup incorrectly? Do I have to look for another Lookup library to do what I need?

+4
source share
1 answer

I have found a solution. The @ServiceProvider annotation @ServiceProvider parsed in some way by the Netbeans IDE and creates a file structure that represents the mapping for services and their implementation. If you work without an IDE capable of doing this (I think only NB does), it will be convenient for you to create these files manually, and the annotation will not work. I would be glad if someone proves their mistake to me, especially for Intellij IDEA.

For information on creating a file structure for using Lookup, see here .

Another way to use the Lookup API outside of a Netbeans platform application could be the AbstractLookup and InstanceContent classes. Look here for how to use them.

+1
source

Source: https://habr.com/ru/post/1499590/


All Articles