JAXB and constructors

前端 未结 4 550
温柔的废话
温柔的废话 2020-12-04 12:28

I\'m starting learning JAXB, so my question can be very silly. Now I have classes and want generate XML Schema. Going after this instruction I get exception

4条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-04 13:18

    You can use the annotation @XmlType and use factoryMethod / factoryClass attributes in various combinations such as:

    @XmlType(factoryMethod="newInstance")
    @XmlRootElement
    public class PurchaseOrder {
        @XmlElement
        private final String address;
        @XmlElement
        private final Customer customer;
    
        public PurchaseOrder(String address, Customer customer){
            this.address = address;
            this.customer = customer;
        }
    
        private PurchaseOrder(){
            this.address = null;
            this.customer = null;
        }
        /** Creates a new instance, will only be used by Jaxb. */
        private static PurchaseOrder newInstance() {
            return new PurchaseOrder();
        }
    
        public String getAddress() {
            return address;
        }
    
        public Customer getCustomer() {
            return customer;
        }
    }
    

    Surprisingly this works and you get an initialized instance when unmarshalling. You should make note not to call the newInstance method anywhere on your code as it will return an invalid instance.

提交回复
热议问题