Oleg’s Weblog

My Tech Rant

Posts Tagged ‘class.forName’

OSGi and Class.forName(..)

Posted by Oleg Zhurakousky on November 5, 2008

While I was presenting “Intro to OSGi” at the recent Philadelphia JUG, I’ve been asked several questions about java class loader dynamics in OSGI environment.  The following post discusses the implication of using Class.forName(..) in OSGi environment.

Let’s say we have the following code:

Class.forName(”org.bar.Foo”);

Usually the same class loader that loaded the class which contains this code will be used. This class loader will follow standard java class loading delegation mechanism to discover and load the class.

However. . .

In the case of the OSGi, each bundle will have its own class loader and outside of java.* packages, this class loader doesn’t follow standard java class loading delegation mechanism and strictly relies on visibility rules and constraint resolution mechanism defined by OSGi – such as providing Import/Export-Package, Required-Bundle and other manifest headers.

This class loader has two responsibilities

  1. Load classes available to the Bundle Space, where Bundle Space = Bundle JAR itself + attached Fragment Bundles
  2. Collaborate with class loaders of other bundles to reach all classes that are visible to a bundle based on OSGi visibility rules and contsraint resolution mechanism. In other words it must colaborate with Bundle’s Class Space, where Bundle’s Class Space = Bundle-Space + Import-Pckage + Import-Bundle etc…

The issue with using Class.forName(..) in the OSGi environment starts when an attempt is made to resolve such Bundle’s Class Space. To do that we have to make sure that the target class is in the Bundle’s Class Space, which means that advertising bundle with proper Export-Package: org.bar.Foo declaration must be available and appropriate dependency strategy is provided in the bundle that relies on such dependency (e.g., Import-Package: org.bar.foo or Require-Bundle: Foo).

The work of discovering dependencies and providing appropriate manifest headers is not a difficult task (after all in the conventional application model all dependent JARs are in the class path) and could be performed manually or using automated tools such as maven-bundle-plugin, by recursively evaluating dependencies of your JAR

However, giving dynamic nature of Class.forName(..) and lack of compile time validation, the target class might not be available or even known at the time of manifest creation, thus making such determination impossible. The result are missing Import/Export-Package, Require-Bundle etc…, headers which creates a nasty problem, when target Class is not available to the Bundle’s Class Space resulting in ClassNotFoundException being thrown.

Advertisements

Posted in osgi | Tagged: , | 7 Comments »