bundle 接口间使用
如bundle1 要导出接口
在配置文件中填写配置信息:
bundle2引用bundle1的service:
接口的使用
- bundle1 接口:
public interface DictionaryService
{
/**
* Check for the existence of a word.
* @param word the word to be checked.
* @return true if the word is in the dictionary,
* false otherwise.
**/
public boolean checkWord(String word);
}
在Activator中注册
package tutorial.example1;
/**
* Implements BundleActivator.start(). Registers an
* instance of a dictionary service using the bundle context;
* attaches properties to the service that can be queried
* when performing a service look-up.
* @param context the framework context for the bundle.
**/
public void start(BundleContext context)
{
Hashtable<String, String> props = new Hashtable<String, String>();
props.put("Language", "English");
context.registerService(
DictionaryService.class.getName(), new DictionaryImpl(), props);
}
另一实现
package tutorial.example2;
public void start(BundleContext context)
{
Hashtable<String, String> props = new Hashtable<String, String>();
props.put("Language", "French");
context.registerService(
DictionaryService.class.getName(), new DictionaryImpl(), props);
}
使用:
import tutorial.example2.service.DictionaryService;
public void start(BundleContext context) throws Exception
{
// Query for all service references matching any language.
ServiceReference[] refs = context.getServiceReferences(
DictionaryService.class.getName(), "(Language=*)");
if (refs != null)
{
try
{
System.out.println("Enter a blank line to exit.");
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String word = "";
// Loop endlessly.
while (true)
{
// Ask the user to enter a word.
System.out.print("Enter word: ");
word = in.readLine();
// If the user entered a blank line, then
// exit the loop.
if (word.length() == 0)
{
break;
}
// First, get a dictionary service and then check
// if the word is correct.
DictionaryService dictionary =
(DictionaryService) context.getService(refs[0]);
if (dictionary.checkWord(word))
{
System.out.println("Correct.");
}
else
{
System.out.println("Incorrect.");
}
// Unget the dictionary service.
context.ungetService(refs[0]);
}
} catch (IOException ex) { }
}
else
{
System.out.println("Couldn't find any dictionary service...");
}
}