JAXB inheritance, unmarshal to subclass of marshaled class

后端 未结 6 952
轮回少年
轮回少年 2020-11-30 21:36

I\'m using JAXB to read and write XML. What I want is to use a base JAXB class for marshalling and an inherited JAXB class for unmarshalling. This is to allow a sender Java

6条回答
  •  执念已碎
    2020-11-30 21:57

    Subclass Person twice, once for receiver and once for sender, and only put the XmlRootElement on these subclassses (leaving the superclass, Person, without an XmlRootElement). Note that sender and receiver both share the same JAXB base classes.

    @XmlRootElement(name="person")
    public class ReceiverPerson extends Person {
      // receiver specific code
    }
    
    @XmlRootElement(name="person")
    public class SenderPerson extends Person {
      // sender specific code (if any)
    }
    
    // note: no @XmlRootElement here
    public class Person {
      // data model + jaxb annotations here
    }
    

    [tested and confirmed to work with JAXB]. It circumvents the problem you note, when multiple classes in the inheritance hierarchy have the XmlRootElement annotation.

    This is arguably also a neater and more OO approach, because it separates out the common data model, so it's not a "workaround" at all.

提交回复
热议问题