There's a simple class Bean1
with a sublist of type 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 { ... }
I am trying to override the class, to change the type of the list.
The new child-class (i.e. BeanChild2
) extends the previous one (i.e. 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 { }
So, here is how I tested it:
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
}
The test reveals that that this list still contains childs of BeanChild1
.
So, how can I force it to populate the childList
field with BeanChild2
instances ?
If there are no easy solutions, then feel free to post more creative solutions (e.g. using XmlAdapter
s, Unmarshaller.Listener
, perhaps an additional annotation on the parent or child class ...)