Class loading dynamically is not performed at runtime

I have the following Java code snippet:

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 strange happens; a is java.lang.NoClassDefFoundErrorthrown on this last line, referring to the class just loaded. The strange part is printlnprinting the exact name of the class.

I checked that if I save the link to the new instance as I Objectmanipulate it only through reflection, everything will be fine, so the offending piece of code should be explicit.

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

PS: For those who want to see a closer stack trace, there is nothing to show:

java.lang.NoClassDefFoundError: org/junit/runner/JUnitCore
  at [last line of example)
  [lines from my app]
Caused by: java.lang.ClassNotFoundException: org.junit.runner.JUnitCore
  at java.net.URLClassLoader$1.run(URLClassLoader.java:200)
  at java.security.AccessController.doPrivileged(Native Method)
  at java.net.URLClassLoader.findClass(URLClassLoader.java:188)
  at java.lang.ClassLoader.loadClass(ClassLoader.java:315)
  at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:330)
  at java.lang.ClassLoader.loadClass(ClassLoader.java:250)
  at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:398)
  at [last line of example]
  [lines from my app]
+3
2

, (, -classpath), JUnit . , JUnit . JUnitCore, JUnitCore, , NoClassDefFoundError .

, , . (1) , JUnitCore, (2) URLClassLoader ( JAR), (3) (4) .

+4

.loadClass("org.junit.runner.JUnitCore", **true**);, resolveClass() ?

-1

Source: https://habr.com/ru/post/1746638/


All Articles