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

强颜欢笑 提交于 2019-12-22 05:27:58

问题


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?


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/8868394/scala-dynamic-class-loading-class-a-can-not-be-cast-to-class-a

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!