(Stuart Halloway)
There was a cool example of writing your own hot-deployment enabled
container: you just load the class on demand each time, and destroy
the Class Loader that loaded it. Thus, the next time you have to load
the class, you have to create a new Class Loader, which re-reads the
class, which picks up your changes.
It was really simple, and while doing it on a whole container level
would be even more difficult, the ease help fuel the fire that we
really don’t need heavy weight containers for everything: we can even
Uncle
Bob it and build some of this stuff ourselves.
Another interesting item was that you can slip in your own Classes
before the bootstrap class loader with a few -X options. That’s crazy!
But, Stu mentioned a time when he couldn’t track down where rouge
classes were coming from, so he wrote his own version of
java.lang.Classloader that printed out where every class
was loaded from.
He didn’t go over writing your own class loaders, which is what I
was really interested in. But, what the hell, the URLClassloader is
probably good enough: anything else (as I’ve learned several times) is
too complicated to be worth it.
To find out where a class was loaded from, by the way, you do
obj.getClass().getProtectionDomain().getCodeBase().getLocation(). Java,
always one to be simple.
Comments
One response to “Class Loading in Java [Lone Star Software Symposium]”
Except that obj.getClass().getProtectionDomain().getCodeSource() can return null. This will happen when obj.getClass().getProtectionDomain().getClassLoader() returns null. In other words, for classes loaded by the bootstrap loader, which includes classes in the endorsed dirs. I tend to use a different approach:
public URL getClassAsResource(Class cls) {
String className = cls.getName();
String classNameAsPath = “/” + className.replace(‘.’, ‘/’);
String classResourceName = classNameAsPath + “.class”;
return cls.getResource(classResourceName);
}
Kris Schneider
kris@dotech.com