inheritence in jaxb-generated classes



I am using jaxb to autogenerate classes for unmarshalling xml content into a java application. I notice that the resulting classes have a lot of redundancy. In particular, the model into which they will ultimately be transferred uses inheritance to avoid the redundancy. I am tempted to re-write all the generated classes so that they also use inheritance. Is there a reason not to do this?


For example:



@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "A", propOrder = {"p1","p2","p3"})
Class A {
@XmlElement(required = true)
property p1;
@XmlElement(required = true)
property p2;
@XmlElement(required = true)
property p3;
}

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "B", propOrder = {"p1","p2","p4"})
class B {
@XmlElement(required = true)
property p1;
@XmlElement(required = true)
property p2;
@XmlElement(required = true)
property p4;
}


would become:



@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "Root", propOrder = {"p1","p2"})
@XmlSeeAlso({A.class, B.class})
Class Root {
@XmlElement(required = true)
property p1;
@XmlElement(required = true)
property p2;
}

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "A", propOrder = {"p3"})
Class A extends Root{
@XmlElement(required = true)
property p3;
}

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "B", propOrder = {"p4"})
Class B extends Root{
@XmlElement(required = true)
property p4;
}


If I make this kind of transformation, will the @Xml... annotations stop working? Will jaxb still be able to unmarshal correctly? If I do not simplify the code as shown above, I think the alternative is to build another set of middle classes to translate the unmarshalled data into my app's model. Anyone care to comment or improve?


No comments:

Post a Comment