Wednesday 24 November 2010

Fun with classloaders

Class loaders are one of those things which work most of the time and you don't have to worry about but when they go wrong they can be a bit of a nuisance to sort out.

When you are running a java application in a application server there are several class loaders in play e.g. for tomcat see http://tomcat.apache.org/tomcat-6.0-doc/class-loader-howto.html
Most of the time this is what you want and any other behaviour would cause problems - think Singletons - however sometimes you are trying to be clever and using a method like Class.forName or ClassLoader.getResource in which case you need a better grasp on what is happening.

In this case you can use Thread.currentThread().getContextClassLoader() or Thread.currentThread().getClass().getClassLoader() as well as Class.getClassLoader to access the different class loaders and hopefully the class/resource which you are after.

No comments: