【发布时间】:2012-03-12 09:02:14
【问题描述】:
我有一些 JAXB 生成的 bean,它们是分层结构的,例如一个 bean 包含其他 bean 的列表。现在我想扩展一些子元素以及包含扩展子元素的父元素。
我的ParentEx 实现了一些其他接口IParent,预计会返回Collection<IChild>。我的ChildEx 实现了IChild。当super.getChild() 返回List<Child> 时,我可以返回(Collection<IChild>)super.getChild() 吗?或者有更好的方法吗?
-
Child和Parent是 JAXB 生成的 bean -
ChildEx和ParentEx是我自己的 bean,用于将 JAXB bean 映射到给定的接口。两个 bean 都覆盖了ObjectFactory -
IChild和IParent是其他库需要的接口
编辑: Eclipse 甚至不允许我从 List<Child> 转换为 List<ChildEx> 所以我必须添加一些丑陋的中间通配符转换 (List<ChildEx>)(List<?>)super.getChild()
【问题讨论】:
-
为什么需要这样做?
List<Child>“是”Collection<Child>在任何情况下。除非我错过了明显的,IParent接口也完全满足任何IChild实现吗? -
谢谢,但不,
Parent有方法List<Child> getChild()和IParent说它需要返回一个Collection<IChild>。因此,我将不得不在我的ParentEx中进行显式转换。我不想修改自动生成的bean,因此为IParent接口安装自动生成的bean 的唯一方法是编写自己的ParentEx implements IParent -
新 ArrayList 的解决方案是否适合您?
标签: java types interface casting jaxb