Search code examples
javaosgiosgi-bundleosgi-fragment

Reflection with OSGI bundles, for Dependent jars


I wrote a framework ( Let's call A), and it depends upon jdbc drivers & data source and loads the classes using reflection.

It uses 3 parametered Class.Forname with Thread.currentThread().getContextClassLoader()

Now, I want to use this framework A.jar inside a OSGI bundle. I've generated Manifest file for A.jar, added the imports & exports properly.

Imports & Exports didn't work because I am loading the class using reflection, So I've used DynamicImport-Package.

But, It works only if I include DynamicImport-Package inside the Bundle which uses A.jar, It doesn't work if I include DynamicImport-Package within the A.jar

I can't have every bundle which uses A.jar to change their manifest file and include DynamicImport.

Can you please help me with this.

PS: I cannot change to statically load the class. I've simplified the problem by omitting certain details, like A.jar actually uses Oracle UCP which uses reflection to load the Datasource.


Solution

  • Class.forName(...) is an anti-pattern in OSGi. Never-ever use it! Thread.currentThread().getContextClassLoader() is the second anti-pattern in OSGi.

    In my opinion, DynamicImport-Package is also an anti-pattern. It is available only to allow already released technologies to work in OSGi (I mean: work as much as they can until an OSGi friendly solution is available for the same problem).

    You managed to use all three of them :).

    OSGi is based on services. Services are based on interfaces (or sometimes classes). Try think of registering an OSGi service on one side and use the service on the other side! Try to define an API that helps you avoiding these patterns!

    You want to work with JDBC drivers. You should read chapter 125 JDBC Service Specification chapter of OSGi compendium specification.

    Try look for "Class.forname OSGi" and "thread.getContextClassLoader OSGi" in google and you will see many useful explonations why they should not be used.

    One of them: http://wiki.osgi.org/wiki/Avoid_Classloader_Hacks

    After you read these articles, you have a better picture, how to design solutions based on OSGi.