From time to time I'm confronted with incompatibilities within OSGi with older libraries and methodologies. The classic example of this is using JDBC libraries directly. The standard method of loading a driver is through the class loader. This simply doesn't work within OSGi the way you think it does. Even if you use the Dynamic-ImportPackage header within your bundle description it's not unusual for your bundle not to be able to find the class.
Another example of this is with using 3rd party libraries like Oracle's optic and application client libraries against J2EE application servers. JaxB usage also has this issue.
So, here's a quick work around that I use. Note that I use the Felix OSGi implementation with iPOJO. However, this should work in any context.
First, get the BundleContext for your component. Within iPojo, it's as simple as creating a constructor where the BundleContext is passed in.
@Component
public class TestComponent {
protected BundleContext bundleContext;
public TestComponent( BundleContext bundleContext) {
this.bundleContext = bundleContext;
}
}
Next I add a simple helper function.
protected OsgiEnvironmentClassLoader getOsgiEnironmentClassLoader(BundleContext bundleContext) {
return new OsgiEnvironmentClassLoader(
bundleContext,
Thread.currentThread().getContextClassLoader(),
bundleContext.getBundle());
}
Then, wherever I need to do something outside of the standard bundle's class loader:
new ClassLoaderContext(getOsgiEnironmentClassLoader(bundleContext)).execute(
new ClassLoaderContextCallback() {
public void doAction() {
/* do something interesting here */
}
});