Very strange cast Casting Exception in EJB (URLClassLoader)

Hello all,

we have developed a J2EE application with a very simple Stateless bean and an application client.

We are trying to create a pluginSystem that will be accessed by the bean. All plugins implement an interface so the bean doesn't need to know the concrete class and can use them casting to the interface.

The problem comes here:

We use URLClassLoader to load a concrete implementation of a Plugin but when casting to the interface a ClassCastExceptions is thrown.

URL[] u =new URL[1];

u[0] =new File(this.plugin_impl_folder).toURL();

URLClassLoader cl =new URLClassLoader(u,ClassLoader.getSystemClassLoader());

Object obj = cl.loadClass("pluginImpl." + p.getImplementedBy()).newInstance();

pluginImplementation pi = (pluginImplementation)obj;//Error comes here

This code works fine when executed locally but fails when being called by the session bean.

It seems that although "obj" is a concrete implementation of the interface "pluginImplementation" it cannot be casted.

Any suggestions?

[1236 byte] By [aaldomaa] at [2007-11-26 21:04:30]
# 1

The solution was found here:

http://www.onjava.com/pub/a/onjava/2003/11/12/classloader.html

" In normal circumstances the ClassCastException thrown when casting classes with the same type but with different effective classloaders is the desired behavior but in some cases we may need the cast to succeed. (...) "

So to solve this problem we had to change the ClassLoader's parent:

URLClassLoader cl = new URLClassLoader(u,this.getClass().getClassLoader());

This way, both classes where loaded by the same ClassLoader, so they where in the same namespace and, finally, considered the same class (no more class cast exceptions thrown).

Easy, when you know it ;)

daguileraa at 2007-7-10 2:37:33 > top of Java-index,Enterprise & Remote Computing,Enterprise Technologies...