本文介绍了Scala - 动态类加载 - 类A不能转换为类A的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的jar文件包含类 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")

没问题,它可以加载类 A 。此命令也可以:

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

clazz.newInstance

但是当我将它转换为 A

clazz.newInstance.asInstanceOf[A]

/ p>

I got this error:

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

您能帮我吗?

推荐答案

在一个classLoader上下文中有A,你正在调用clazz.newInstance.asInstanceOf [A],这是一个单独的上下文,从中获取clazz对象。 问题是在两个不同的classLoader上下文中有两个不同的类A的实例。从类A的一个版本创建的对象不能被转换为其他类的实例版本在不同的classLoader上下文。

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.

这篇关于Scala - 动态类加载 - 类A不能转换为类A的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-11 01:39