【发布时间】:2021-03-17 09:26:15
【问题描述】:
我目前面临 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.generics.GenericTest$ChildEntity 类(com.generics.GenericTest$Parent 和 com.generics.GenericTest$ChildEntity 位于加载程序“app”的未命名模块中) java.lang.ClassCastException:类 com.generics.GenericTest$Parent 不能强制转换为类 com.generics.GenericTest$ChildEntity(com.generics.GenericTest$Parent 和 com.generics.GenericTest$ChildEntity 位于加载程序'app 的未命名模块中')
我想知道为什么它会失败,因为我们强制 Child 必须是Parent 类型。
为什么会出现问题以及如何解决?
【问题讨论】:
标签: java generics inheritance classcastexception