Search code examples
classscaladynamicclassloaderloading

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?


Solution

  • 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.