Consuming Services from Embedded OSGi Framework

2019-02-21 00:55发布

问题:

I have embeddable Felix. I have some API bundle and Impl. API exports interface C.Impl imports that interface and register impl in activator. Now I want get C impl otside OSGi

  FrameworkFactory ff = new FrameworkFactory();
  ...
  BundleContext bc = fwk.getBundleContext();
  ...
  final ServiceReference[] serviceReferences = bc.getServiceReferences(C.class.getName(), "(objectclass=" + C.class.getName() + ")");
  for(ServiceReference serviceReference : serviceReferences){
     final Object service = bc.getService(serviceReference);
     ...
  }

Now I want to interact with it. I can do it with reflection

     System.out.println(service.getClass().getMethod("some").invoke(service)); //using 

But I can't cast it

     System.out.println(service instanceof C); //prints false

I guess that comes from different ClassLoaders. But how I can solve it? How we can interract with OSGi context from outside? Or we can obly put it all into OSGi container?

回答1:

If you are embedding OSGi, the API for the service (i.e. interface "C") has be to visible to the outer application and exported into OSGi via the system bundle exports. The outer application cannot import packages from the bundles contained inside the OSGi framework.



标签: java osgi