0

I have an Interface called 'Foo' and i have a bundle 'b'.

Now I want to get all classes implementing interface 'Foo' in bundle b

Something like below

org.osgi.framework.Bundle bundle = ...;
List<Class<? extends Foo>> allImplemetation = getAllImplementation(bundle);
pgollangi
  • 848
  • 3
  • 13
  • 28
  • Why do you want to do this? Is it for some kind of extensibility mechanism? – Christian Schneider Jan 22 '16 at 08:05
  • I'm doing a small where user's can install (this is not BundleContext.install) bundles. Here I want to invoke a method on all implementations of Foo in user's installed bundles. – pgollangi Jan 22 '16 at 09:24

1 Answers1

4
  1. The clean way to find implementations in OSGi is to let each bundle publish each implementation as an OSGi service. This allows to keep the impl classes private and makes sure your central bundle is nicely decoupled from the user bundles. Here you can find some guidance how to do this .

  2. If this is not possible then you can use a BundleTracker to get a call back when new bundles are installed. You can then use Javassist or XBean finder to scan the bundle class path for classes that implement and interface. This variant is pretty difficult to do right though. So I would try to avoid it.

  3. A kind of a middle of the road solution would be to use the same approach as ServiceLoader. You create a file at a special directory in the jars that contains the class names of the implementations to load. You can then use the BundleTracker like above to find the newly installed bundle, read this resource and then use the ClassLoader of the bundle to load the implementation class.

Community
  • 1
  • 1
Christian Schneider
  • 19,420
  • 2
  • 39
  • 64
  • I would strongly recommend sticking with the service approach (no 1). If a bundle wants to offer a class it should opt in by publishing it as a service. The alternative of having another bundle rummage around in your internals is too intrusive and may produce unexpected behaviour. – Neil Bartlett Jan 22 '16 at 17:47
  • I'm going with first approch – pgollangi Jan 23 '16 at 05:01