【发布时间】:2015-04-23 23:23:26
【问题描述】:
我有一个使用泛型实现接口的类。
class MainClass {
interface MyInterface <T extends MyInterface.A> {
static class A {
}
}
}
//I have another class which implements this interface:
class ImplementingClass implements MyInterface<A> {
}
//I am loading MyInterface class from a jar in a different place:
static loadJar(){
String dexPath = new ContextWrapper(context).getCacheDir().getAbsolutePath();
DexClassLoader classLoader = new DexClassLoader(JAR_FILE, dexPath, null, ClassLoader.getSystemClassLoader());
Class c = classLoader.loadClass("ImplementingClass");
MyInterface nvQS = (MyInterface) c.newInstance();
}
我得到一个类转换异常。我不确定这是为什么?该类正在实现接口。我也尝试过使用泛型,但仍然遇到异常。
如果我不清楚,请告诉我。谢谢。
包括例外: java.lang.ClassCastException:ImplementingClass 无法转换为 MainClass$MyInterface
嘿,接口是在android中构建为java静态库的。 jar 和 jar 加载器将针对单独的副本进行编译,对吗?那是问题吗?你认为这就是为什么我可能会得到一个班级演员吗?
【问题讨论】:
-
您遇到的异常是什么?您尚未提供堆栈跟踪。通常,异常中的错误消息会相当明确地告诉您问题所在。
-
你使用IDE吗?我建议您使用调试来查看对象“c”。看看它的类。
-
是的,我做到了。 "加载类的名称:ImplementingClass"
-
如果你在外部 jar 文件中有 MyInterface,你怎么可能编译 MyInterface nvQS = (MyInterface) c.newInstance(); ?这意味着您的项目中有一个 MyInterface,外部 jar 文件中有一个 MyInterface,因此即使它们具有完全相同的签名,也会有两个不同的类。
标签: java android classcastexception