Tuesday, March 13, 2007

ClassLoader and the order of classpath entries

JBossAOP provides runtime aspectization feature. For this it has a classloader instrumentor which modifies the java.lang.ClassLoader which will intercept the call and invoke the interceptor chain.

Based on their docs
java -Xbootclasspath/p:<aop boot classpath as described> \
-Djboss.aop.path=<path to jboss-aop.xml> \
-classpath <path to your classes> com.blah.MyMainClass
The above command is used to execute a java class with the instrumented classloader. When i used this command, i had the bootclasspath as
(through eclipse) JRE Classpath;{generated ClassLoader};{JBossAOP jars};
It dint work as expected, that is the interceptors weren't invoked.

Then i remembered of ClassLoaders and the way it loads the classes. That is it searches the given paths, one by one and loads the class. Then i changed the order of the entries as {generated ClassLoader};{JBossAOP jars};JRE Classpath;. Now everything worked fine and the result was as expected.

The important point to remember is that, if you have duplicate classes like the one used above, java.lang.ClassLoader, the order of the desired class (instrumented ClassLoader) in the classpath should be at the top so that it will be loaded before other duplicate gets loaded.

Lesson learnt: order of the classpath entries is very important