Roberto Linares
Roberto Linares

Reputation: 2225

Java Load Class Dinamically in ChildClassLoader related to SystemClassLoader

I have a java web application that comes wiht a abstract class, (lets call it ClassA) deployed on an application server. This java web application also loads classes from external jars dinamically, by using the approach on this question's accepted response.

Everything works fine, until I get to load a class (call it, ClassB) that extends from ClassA. I get a java.lang.ClassNotFoundException: ClassA error message on my SysOut, pointing to the line that loads the class: urlClassLoader.loadClass(className);.

I assumed I wouldn't have a problem, since when I call URLClassLoader.newInstance(), it gets created from the default parent class loader, which I suppose should be the SystemClassLoader, which I assume contains the WebApp classes.

I tried changing the deployment configuration of my WebApp from parent first to parent last and got the same error. I also tried doing a Class.forName("ClassA") before executing the URLClassLoader.loadClass("ClassB") line but got the same error again.

Upvotes: 0

Views: 254

Answers (1)

AdamSkywalker
AdamSkywalker

Reputation: 11609

It seems that ClassA is loaded by some container's WebAppClassLoader which is a child of SystemClassLoader. Your custom URLClassLoader is a child of SystemClassLoader too and that's the reason why ClassB doesn't "see" ClassA.

To solve the problem, ClassB should be loaded by WebAppClassLoader or its child, it can be achieved with:

ClassLoader webAppCL = ClassA.class.getClassLoader();
URLClassLoader myCL = new URLClassLoader(urls, webAppCL);

Upvotes: 1

Related Questions