ClassCastException "Parent cannot be cast to class...are in unnamed module of loader 'app' " with



我目前正面临Java中泛型的问题。我需要返回一个广播给子实例的父实例。

下面的示例展示了我正在努力实现的目标。

public class GenericTest {
@Test
public void test() {
assertEquals("child", new B().returnParentInstanceAsChild().name());
}
public static class Parent {
public String name() {
return "parent";
}
}
public static abstract class A<Child extends Parent> {
public Child returnParentInstanceAsChild() {
return (Child) new Parent();
}
}
public static class ChildEntity extends Parent {
@Override
public String name() {
return "child";
}
}
public static class B extends A<ChildEntity> {
}
}

此代码不贯穿始终,而是生成以下异常:

类com.generics.GenericTest$Parent不能强制转换为类com.genetics.GenericTest$ChildEntity(com.generics.GenericTest$Parent和com.generics.GenericTest$ChildEntity位于加载程序"app"的未命名模块中(java.lang.ClassCastException:类com.generics.GenericTest$Parent不能强制转换为类com.geneerics.GenericTest$ChildEntity(com.generics.cGenericTest$CParent和com.generics.GenericTest$ChildEntity位于加载程序"app"的未命名模块中(

我想知道它为什么会失败,因为我们已经强制执行了子需要为类型。

为什么会出现问题,如何解决

此操作失败的原因与以下行失败的原因相同:

ChildEntity child = (ChildEntity) new Parent();

在运行时,转换将失败,因为Parent不是ChildEntity

您可能想让子类负责创建子实例,这样您就可以让父类方法抽象化:

public static abstract class A<T extends Parent> {
public abstract T returnParentInstanceAsChild();
}
public static class B extends A<ChildEntity> {
@Override
public ChildEntity returnParentInstanceAsChild() {
return new ChildEntity();
}
}

相关内容

最新更新