ClassCastException "Parent cannot be cast to class...are in unnamed module of loader 'app' " 与 Java 泛型和继承

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

我目前在 Java 中遇到泛型问题。我需要 return 将父实例强制转换为子实例。

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

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> {
    }

}

此代码未 运行 通过并产生此异常:

class com.generics.GenericTest$Parent cannot be cast to class com.generics.GenericTest$ChildEntity (com.generics.GenericTest$Parent and com.generics.GenericTest$ChildEntity are in unnamed module of loader 'app') java.lang.ClassCastException: class com.generics.GenericTest$Parent cannot be cast to class com.generics.GenericTest$ChildEntity (com.generics.GenericTest$Parent and com.generics.GenericTest$ChildEntity are in unnamed module of loader 'app')

我想知道为什么它会失败,因为我们强制 Child 需要是 Parent 类型.

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

这与下面一行失败的原因相同:

ChildEntity child = (ChildEntity) new Parent();

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

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

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