Pushing the envelope

Darren's take on Java, agile methods, cool open source stuff, interesting technologies and other random wanderings through the land of blog.
Updated: 26/01/2003; 11:50:01.
Places to go
Apache Jakarta Project
c2.com
ExtremeProgramming.org
OpenSymphony
XProgramming.com
XP Developer

People to see
Russell Beattie
Eugene Belyaev
Tony Bowden
Mike Cannon-Brookes
Jeff Duska
Paul Hammant
Scott Johnson
Brett Morgan
Rickard Öberg
James Strachan
Joe Walnes

Things to do

Subscribe to "Pushing the envelope" in Radio UserLand.

Click to see the XML version of this web page.

Click here to send an email to the editor of this weblog.


That was the day
September 2002
Sun Mon Tue Wed Thu Fri Sat
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30          
Aug   Oct



Archives
December 2002
November 2002
October 2002
September 2002
August 2002

Listening To


Valid RSS

Click here to visit the Radio UserLand website.

  24 September 2002

Class.forName() is evil....

We've all done it before I guess. Called Class.forName( "com.foo.MyClass" ) to load some class at runtime based on some configurable class name. At first it seems very groovy.

However this does not work very well in application servers, containers or various environments like Maven, Ant, JUnit etc. The days of everything being in the system class loader are over, now we need to live in a multiple-classloader world.

Solution? Try use the current thread's context class loader or the class loader used to load your code. So try replace this...

Class theClass = Class.forName( className );

with this more verbose version (which could easily be wrapped in a helper method)

Class theClass = null;
try {
    theClass = Thread.currentThread().getContextClassLoader().loadClass( className );
}
catch (ClassNotFoundException e) {
    theClass = getClass().getClassLoader().loadClass( className );
}

Henri, this could be a possible addition to commons lang?

While we're talking about living in multi-classloader worlds, bob's new project ClassWorlds looks very groovy.

[James Strachan's Radio Weblog]

This certainly goes a long way towards solving classloader issues - I always seem to get bitten by XML parsers in this regard. What it doesn't always solve is the situation of colliding packages. I've hit a situation where the app. server is using a version of Xerces thats older than the version my app. wants to use. This gets messy, and the exact behaviour depends on your app. server's classloading policy (it doesn't help that the servlet spec. appears to be in conflict with the java language spec. on the issue of classloader delegation order).


9:43:16 AM      comment []

© Copyright 2003 Darren Hobbs