Question

I have multiple compiled Java class files from various packages in a directory, like so.

C:/classes/package/A.class

C:/classes/package/B.class

C:/classes/package/subpackage/C.class

C:/classes/package/subpackage/D.class

I'm attempting to load them using a URLClassloader like so.

URLClassloder classloader = new URLClassLoader(new URL[]{new File("C:/classes/").toURI().toURL()});
System.out.println("Loading classes...");
classloader.loadClass("package.A");
classloader.loadClass("package.B");
classloader.loadClass("package.subpackage.C");
classloader.loadClass("package.subpackage.D");
System.out.println("Loaded classes.");

This code runs fine until I try to load "package.subpackage.D". The program permanently hangs.

Changing the order in which the classes were loaded had no effect but, after much experimentation, I found that any class extending a native class would cause such a hang, "native" referring to all classes already within the runtime.

So here are my questions:

Is this the right way to load classes during runtime?

Is there a fix to the problem?

Thank you for your time.

Was it helpful?

Solution

Your URLClassLoader needs a parent which knows how to load the JDK classes. The parent loader should probably be borrowed from the context, i.e.:

new URLClassLoader(urls, this.getClass().getClassLoader()) 

See URLClassLoader(URL[], ClassLoader).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top