JAXB inheritance, unmarshal to subclass of marshaled class

后端 未结 6 942
轮回少年
轮回少年 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 22:16

    You're using JAXB 2.0 right? (since JDK6)

    There is a class:

    javax.xml.bind.annotation.adapters.XmlAdapter
    

    which one can subclass, and override following methods:

    public abstract BoundType unmarshal(ValueType v) throws Exception;
    public abstract ValueType marshal(BoundType v) throws Exception;
    

    Example:

    public class YourNiceAdapter
            extends XmlAdapter{
    
        @Override public Person unmarshal(ReceiverPerson v){
            return v;
        }
        @Override public ReceiverPerson marshal(Person v){
            return new ReceiverPerson(v); // you must provide such c-tor
        }
    }
    

    Usage is done by as following:

    @Your_favorite_JAXB_Annotations_Go_Here
    class SomeClass{
        @XmlJavaTypeAdapter(YourNiceAdapter.class)
        Person hello; // field to unmarshal
    }
    

    I'm pretty sure, by using this concept you can control the marshalling/unmarshalling process by yourself (including the choice the correct [sub|super]type to construct).

提交回复
热议问题