ClassCastException: Class 实现了接口,仍在进行类转换

ClassCastException: Class implementing the interface, still getting classcast

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

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();
}

我得到一个 class 转换异常。我不确定这是为什么? class 正在实现接口。我也用泛型尝试过,但我仍然遇到异常。

如果我不清楚,请告诉我。谢谢

包括异常: java.lang.ClassCastException: ImplementingClass 无法转换为 MainClass$MyInterface

嘿,界面在 android 中构建为 java 静态库。 jar 和 jar 加载器将针对单独的副本进行编译,对吧?那是问题吗?你认为这就是为什么我可能会得到 class 演员阵容的原因吗?

您正在创建一个新界面 MainClass.MyInterface,它与 MyInterface 不同。如果您实现 MainClass.MyInterface 并且还转换为 MainClass.MyInterface 那么它应该可以工作。选择更好的名称可能可以避免这种情况。

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

所以问题是接口是一个静态库。因此,由于 jar 和加载它的代码是分开编译的,因此 java 认为它们不相同 class。我把它变成了一个共享库,它工作正常,也不例外。 :-)