Dynamic classloading fails on runtime

Posted by Henrik Paul on Stack Overflow See other posts from Stack Overflow or by Henrik Paul
Published on 2010-05-21T22:57:26Z Indexed on 2010/05/21 23:00 UTC
Read the original article Hit count: 287

Filed under:
|
|
|

I have the following snippet of java code:

final Class<?> junitCoreClass = AccessController.doPrivileged(
    new PrivilegedAction<URLClassLoader>() {
      @Override
      public URLClassLoader run() {
        return new URLClassLoader(new URL[] { junitJarUrl });
      }
    }).loadClass("org.junit.runner.JUnitCore");

System.out.println(junitCoreClass.getName());
final JUnitCore junitCore = (JUnitCore) junitCoreClass.newInstance();

This compiles fine. But when I try to run it, something weird happens; a java.lang.NoClassDefFoundError is thrown on that last line, referring to the class just loaded. The weird part is, the println prints the exact class name.

I checked that if I keep the reference as an Object and manipulate it only through reflection, everything's fine, so the offending piece of code must be the explicit cast.

Can someone explain to me why this happens, and also tell me how I can achieve what I'm trying to do?

© Stack Overflow or respective owner

Related posts about java

Related posts about dynamic