Monday, November 1, 2010

Dynamic Class Loading in OSGi

Sometimes you need to load an arbitrary class which you don't know in advance. In a normal Java application you would do that with Class.forName(String className). But in OSGi this will work only if your bundle imports explicitly the package of the class that you wish to load. In OSGi each bundle has its own class loader. OSGi services will not help if the class you wish to load is not exposed as a service, which is more likely the case.
It would be great if at run-time you could find the bundle exporting the package of the desired class and ask that bundle to load the class using its own class loader.
It turns out this is possible via PackageAdmin service.

org.osgi.service.packageadmin.PackageAdmin packageAdmin;
Class clazz = packageAdmin.getExportedPackage(packageName)

Here packageName is the package name and className is the full class name.
This way you can load any class from any package exported by any active bundle and still your bundle is independent from the bundle providing the class. This could be very useful when implementing some generic functionality like object persistence.

1 comment:

  1. ya this is the best way. But say there are Two bundles A and B. B is having class which extend an abstract class in Bundle A.
    Now when I put the above code in Bundle A to load class in Bundle B, it gives NOClassDefFoundError for BundleA.abstractclass