Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/211.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java ClassCastException:实现接口的类,仍然获得classcast_Java_Android_Classcastexception - Fatal编程技术网

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

Java ClassCastException:实现接口的类,仍然获得classcast,java,android,classcastexception,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&g

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

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类main类{
接口MyInterface{
静态A类{
}
}
}
//我有另一个实现此接口的类:
类实现类实现MyInterface{
}
//我正在从另一个地方的jar加载MyInterface类:
静态loadJar(){
字符串dexPath=new ContextWrapper(context).getCacheDir().getAbsolutePath();
DexClassLoader classLoader=新的DexClassLoader(JAR_文件,dexPath,null,classLoader.getSystemClassLoader());
c类=classLoader.loadClass(“实现类”);
MyInterface nvQS=(MyInterface)c.newInstance();
}
我得到一个类强制转换异常。我不知道这是为什么?类正在实现接口。我也尝试过使用泛型,但还是得到了例外

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

包括例外情况: java.lang.ClassCastException:无法将ImplementingClass强制转换为MainClass$MyInterface


嘿,这个接口是在android中作为java静态库构建的。jar和jar加载器将根据单独的副本进行编译,对吗?这是个问题吗?你认为这就是为什么我可能会得到一个班级演员

您正在创建一个新接口
MainClass.MyInterface
,它与
MyInterface
不同。如果您实现了
MainClass.MyInterface
,并且还强制转换为
MainClass.MyInterface
,那么它应该可以工作。选择更好的名字或许可以避免这种情况


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

因此问题在于接口是一个静态库。因此,由于jar和加载jar的代码是分别编译的,java并不认为它们是同一个类。我把它做成了一个共享库,它运行得很好,也不例外。:-)

你得到的例外是什么?您尚未提供堆栈跟踪。通常异常中的错误消息会非常明确地告诉您问题所在。您使用IDE吗?我建议您使用Debug来查看对象“c”。看,这是课堂。是的,我做到了。“加载类的名称:ImplementingClass”如果您在外部jar文件中有MyInterface,您如何能够编译MyInterface nvQS=(MyInterface)c.newInstance()?这意味着在项目中有一个MyInterface,在外部jar文件中有一个MyInterface,因此即使它们具有完全相同的签名,也有两个不同的类。所以在使用时我可以直接使用接口名,对吗?也许这不是问题所在?也为这些名字道歉。我以为我是在简化。下次我会保留原来的名字。谢谢。@user2248720据我所知,如果你的接口在另一个类中,你就不能这样做。然后您需要编写包含前面接口的类。可以跳过这些包。也许这取决于java版本。那么这也会给我带来一个编译器错误,对吗?它编译得很好。我使用的是Java版本7@user2248720不,如果两者都存在,就不会有。试试看,嘿,我试过了。我仍然得到错误信息(