Dynamic classloading fails on runtime
- by Henrik Paul
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?