【发布时间】:2016-07-13 09:44:33
【问题描述】:
有一个简单的类Bean1,其子列表类型为BeanChild1。
@XmlRootElement(name="bean")
@XmlAccessorType(XmlAccessType.PROPERTY)
public static class Bean1
{
public Bean1()
{
super();
}
private List<BeanChild1> childList = new ArrayList<>();
@XmlElement(name="child")
public List<BeanChild1> getChildList()
{
return childList;
}
public void setChildList(List<BeanChild1> pChildList)
{
childList = pChildList;
}
}
public static class BeanChild1 { ... }
我正在尝试覆盖类,以更改列表的类型。
新的子类(即BeanChild2)扩展了前一个子类(即BeanChild1)。
public static class Bean2 extends Bean1
{
public Bean2()
{
super();
}
@Override
@XmlElement(name="child", type=BeanChild2.class)
public List<BeanChild1> getChildList()
{
return super.getChildList();
}
}
public static class BeanChild2 extends BeanChild1 { }
所以,我是这样测试的:
public static void main(String[] args)
{
String xml = "<bean>" +
" <child></child>" +
" <child></child>" +
" <child></child>" +
"</bean>";
Reader reader = new StringReader(xml);
Bean2 b2 = JAXB.unmarshal(reader, Bean2.class);
assert b2.getChildList().get(0) instanceof BeanChild2; // fails
}
测试表明该列表仍包含BeanChild1 的子级。
那么,我怎样才能强制它用BeanChild2 实例填充childList 字段?
如果没有简单的解决方案,请随时发布更多有创意的解决方案(例如使用XmlAdapters、Unmarshaller.Listener,也许在父类或子类上附加注释......)
【问题讨论】:
标签: java jaxb unmarshalling xmladapter