ClassCastException:实现接口的类,仍然获得classcast

时间:2015-04-23 23:23:27

标签: java android classcastexception

我有一个正在实现泛型接口的类。

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 loader将针对单独的副本编译对吗?那是问题吗?你认为这就是为什么我可能会上课吗?

2 个答案:

答案 0 :(得分:0)

您正在创建一个与MainClass.MyInterface不同的新界面MyInterface。如果您实施MainClass.MyInterface并投射到MainClass.MyInterface那么它应该有效。选择更好的名字可能会避免这种情况。

不要与包混淆,如果包含MainClass,可以跳过它们。

答案 1 :(得分:0)

所以问题是界面是一个静态库。因为jar和它加载的代码是分开编译的,所以它们不被java视为同一个类。我把它做成了一个共享库,它运行正常,也不例外。 : - )

相关问题