栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

JAXB和构造函数

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

JAXB和构造函数

JAXB可以使用XML适配器来支持这种情况。考虑您具有以下对象,没有零参数构造函数:

package blog.immutable;public class Customer {    private final String name;    private final Address address;    public Customer(String name, Address address) {        this.name = name;        this.address = address;    }    public String getName() {        return name;    }    public Address getAddress() {        return address;    }}

您只需要创建此类的可映射版本:

package blog.immutable.adpater;import javax.xml.bind.annotation.XmlAttribute;import blog.immutable.Address;public class AdaptedCustomer {    private String name;    private Address address;    @XmlAttribute    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }    public Address getAddress() {        return address;    }    public void setAddress(Address address) {        this.address = address;    }}

还有一个在它们之间转换的XML适配器:

package blog.immutable.adpater;import javax.xml.bind.annotation.adapters.XmlAdapter;import blog.immutable.Customer;public class CustomerAdapter extends XmlAdapter<AdaptedCustomer, Customer> {    @Override    public Customer unmarshal(AdaptedCustomer adaptedCustomer) throws Exception {        return new Customer(adaptedCustomer.getName(), adaptedCustomer.getAddress());    }    @Override    public AdaptedCustomer marshal(Customer customer) throws Exception {        AdaptedCustomer adaptedCustomer = new AdaptedCustomer();        adaptedCustomer.setName(customer.getName());        adaptedCustomer.setAddress(customer.getAddress());        return adaptedCustomer;    }}

然后,对于引用Customer类的属性,只需使用@XmlJavaTypeAdapter批注:

package blog.immutable;import javax.xml.bind.annotation.XmlRootElement;import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;import blog.immutable.adpater.CustomerAdapter;@XmlRootElement(name="purchase-order")public class PurchaseOrder {    private Customer customer;    @XmlJavaTypeAdapter(CustomerAdapter.class)    public Customer getCustomer() {        return customer;    }    public void setCustomer(Customer customer) {        this.customer = customer;    }}

有关更详细的示例,请参见:

  • http://bdoughan.blogspot.com/2010/12/jaxb-and-immutable-objects.html


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/451317.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号