Help: ClassLoader and Casting??

J

John Davison

I need to load a different version of a class than what is being used
by the overall system. My test code works fine for loading the class,
but fails when I try to cast the Object. For example, the following
throws a java.lang.NoClassDefFoundError when trying to cast.

public class URLTester
{
public static void main( String args[] ) throws Exception
{
// Create an array of URLs
// From directory name specified as args[0]
URL urlList[] = {new File( args[ 0 ] ).toURL()};

// Create a URLClassLoader
ClassLoader loader = new URLClassLoader( urlList );
// Thread.currentThread().setContextClassLoader( loader );

// Load class from class loader
// Use args[1] as class name
Class c = loader.loadClass( args[ 1 ] );

// Create an instance of the class just loaded
Object obj = c.newInstance();

// This fails with a NoClassDefFoundError
Tester tester = (Tester)obj;
}
}

My hunch is that the system ClassLoader is doing the casting. I've
tried, with no success, to add
Thread.currentThread().setContextClassLoader( loader ) to change the
thread's ClassLoader.

Any help would be greatly appreciated!

-- John
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,767
Messages
2,569,572
Members
45,045
Latest member
DRCM

Latest Threads

Top