But sometimes I need an OSGi service or the BundleContext also in non OSGi / DS controlled class. E.g. when I like to write a JAX-WS web service class. There are many ways to get the Bundle Context into this type of Objects. One is to get the Bundle Context from the ClassLoader (which should implements the BundleReference interface). Here a short demo code snippet how to get the bundle API and also the bundle context of a class.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import org.osgi.framework.BundleContext; | |
import org.osgi.framework.BundleReference; | |
import org.osgi.framework.ServiceReference; | |
import org.osgi.service.packageadmin.PackageAdmin; | |
public class MyDemoClass | |
{ | |
public PackageAdmin getService() | |
{ | |
// Howto get a bundle context | |
BundleContext ctx = | |
BundleReference.class.cast(MyDemoClass.class.getClassLoader()) | |
.getBundle() | |
.getBundleContext(); | |
// Only demo code ugly service handling | |
ServiceReference serviceReference = ctx.getServiceReference(PackageAdmin.class.getName()); | |
return PackageAdmin.class.cast(ctx.getService(serviceReference)); | |
} | |
} |
Comment: "However, this requires the code to have the permission to access the class loader." OSGi Core Specification see section 3.8.9.
Better implementation (thanks at Holger for the hint) is by using the OSGi FrameworkUtil class. See the second code snippet:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import org.osgi.framework.BundleContext; | |
import org.osgi.framework.FrameworkUtil; | |
import org.osgi.framework.ServiceReference; | |
import org.osgi.service.packageadmin.PackageAdmin; | |
public class MyDemoClass | |
{ | |
public PackageAdmin getService() | |
{ | |
// get bundle instance via the OSGi Framework Util class | |
BundleContext ctx = FrameworkUtil.getBundle(MyDemoClass.class).getBundleContext(); | |
ServiceReference serviceReference = ctx.getServiceReference(PackageAdmin.class.getName()); | |
return PackageAdmin.class.cast(ctx.getService(serviceReference)); | |
} | |
} |
Another solution could be a holder class with a static field, which holds the actual bundle context instance. This also works when the code does not have the permission to access the class loader.