2007-07-24

Sharing classes with modules and non-module based JARs in a NetBeans RCP Application

Sometimes, such as when using JPA or Hibernate from more than one module, it is necessary to share classes between any number of modules and non-module based libraries/JARs in a NetBeans RCP/Platform based application. The reason this solution is needed is because some libraries, and even at times modules, need to be able to see classes from other libraries and modules at runtime to use certain patterns and these classes and modules have a cyclic dependency because of the type of classes being used. JPA or Hibernate are perfect examples where the entity manager will reside in one library and needs to be able to create instances of classes from another library or module, which also references other JPA or Hibernate classes themselves, using annotations or XML descriptors. This usually happens dynamically at runtime in these type situations.

In NetBeans the module system provides good separation. The problem is this can at times be too strict. To work around this issue you need to create a custom platform and then find the platform#/core directory under the platform directory and put the libraries and JARs in it. I will update this later to explain how to setup a custom platform.

Once you have the libraries in the core directory they can be used by any module or other library at runtime. These JARs can be copied to the core folder at build time and before distribution using ANT, so it is a good idea to make this custom platform reside relative to your project. Another good reason to have them reside relative to the project is that these common JAR files will have to be referenced by your module projects. To reference these JARs from your module projects you will have to edit project.properties and add a property:
cp.extra

which is a colon delimited list of JAR files needed for the classes the particular module needs to reference. Once cp.extra is setup, any errors you may see in the Java editor, related to these classes, should disappear and you can actually compile your project.

It is best to avoid doing this if possible as it removes the ability to use different versions of the same libraries by different modules while also removing the ability to auto-update these libraries, but when it is not possible to avoid such things then they are certainly needed. You wouldn't shoot yourself in the foot for spite, nor do I suspect you would not complete your project just because it best to not step outside the bounds of the regular module class loaders.

No comments: