user942821
user942821

Reputation:

Scala - Dynamic class loading - class A can not be cast to class A

I have a simple jar file containing class A:

public class A {}

Then I load it in runtime:

var classLoader = new URLClassLoader(Array(my_jar_file.toURI.toURL))
var clazz = classLoader.loadClass("A")

It is ok, it can load the class A. This command is also ok:

clazz.newInstance

But when I cast it to A:

clazz.newInstance.asInstanceOf[A]

I got this error:

java.lang.ClassCastException: A cannot be cast to A

Could you please help me?

Upvotes: 7

Views: 8094

Answers (2)

DilipJoseph
DilipJoseph

Reputation: 53

I experienced a very similar problem, in that I observed a ClassCastException when casting a dynamically loaded object to an interface implemented by it.
Thanks to Neil's answer, I was able to determine that the ClassCastException was caused by having different class loader contexts.

To fix this I used the URLClassLoader(URL[] urls, ClassLoader parent) constructor instead of the URLClassLoader(URL[] urls) constructor.

Upvotes: 4

Neil Essy
Neil Essy

Reputation: 3607

Your code implies that you have "A" available in one classLoader context where you are calling clazz.newInstance.asInstanceOf[A] which is a separate context from where you are getting the clazz object. The problem is that you have two different instances of the class "A" in two different classLoader contexts. An object that is created from one version of class "A" cannot be cast to an instance of the other version in a different classLoader context.

Upvotes: 5

Related Questions