Custom Java ClassLoaders- Don't Do It!
I've been working with Java for about 8 years or so
and about once per year I come across someone who tries to write a custom ClassLoader. Here's my rule: If you aren't an app server, don't write a new ClassLoader implementation.
Normally the attempt is made for a very good reason, there's no "hot reloading" of Class definitions in Java by default. It sounds really easy to add some checks to a ClassLoader to see if a .class file's time stamp has changed or to add a flush system. I would love for this to exist. I would use it in a heart beat. Jakarta, BEA, JBoss, IBM and Oracle should add this functionality. But there's a reason why there is no project in Jakarta commons
: ClassLoader hierarchies can be very complex.
Here's a recent scenario. I use OAS and WebSphere a lot to deploy and test my apps. I use JAAS for authentication. This normally works fine because OAS and WAS allow for you to change the ClassLoader hierarchy to check the current loader before the parent. So when I use JAAS within my ear, the LoginModule classes can be stored in the ear, instead of at the app server or system ClassLoader level. This is different than the default behavior that Sun suggest, but is highly useful. As without this function, I couldn't use JAAS to authenticate (I can't put my classes in the app or system classpath for reasons I'll explain some other day).
I'm using an embedded service engine, that I won't name but is pretty cool, and it builds it's own Threads and ClassLoaders. But it does it like Sun says you should, not how OAS and WAS do it. So this means that when I try to use classes that live in the app or system classpath (like OAS' and WAS' JAAS frameworks- implicitly called by LoginContext.login), I get a bunch of NoClasDefFoundErrors
. And there's really no work around than to drop my entire class library in the app or system classpath, which I can't do. So this app that I have to embed and use is sucking a bit because it can't call out classes stored in the very ear that is running the app. The effort was good-hearted, but it caused me extra work to hack around it.
So my plea is this: Don't mess with ClassLoaders, you can't do it. If you are a genius and make the perfect ClassLoader, start a project in commons so the world can benefit and I don't have to muck around in near-genius code that doesn't quite make it.