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

JAXB避免保存默认值

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

JAXB避免保存默认值

您可以通过

XmlAccessorType(XmlAccessType.FIELD)
在get / set方法中使用逻辑并将逻辑放入其中来执行以下操作:

package forum8885011;import javax.xml.bind.annotation.*;@XmlRootElement@XmlAccessorType(XmlAccessType.FIELD)class Example {    private static final String PROP1_DEFAULT = "default1";    private static final String PROP2_DEFAULT = "123";    @XmlElement(defaultValue=PROP1_DEFAULT)    String prop1;    @XmlElement(defaultValue=PROP2_DEFAULT)    Integer prop2;    public String getProp1() {        if(null == prop1) { return PROP1_DEFAULT;        }        return prop1;    }    public void setProp1(String value) {        if(PROP1_DEFAULT.equals(value)) { prop1 = null;        } else { prop1 = value;        }    }    public int getProp2() {        if(null == prop2) { return Integer.valueOf(PROP2_DEFAULT);        }        return prop2;    }    public void setProp2(int value) {        if(PROP2_DEFAULT.equals(String.valueOf(value))) { prop2 = null;        } else { prop2 = value;        }    }}

演示版

package forum8885011;import javax.xml.bind.*;public class Demo {    public static void main(String[] args) throws Exception {        JAXBContext jc = JAXBContext.newInstance(Example.class);        Marshaller marshaller = jc.createMarshaller();        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);        Example example = new Example();        example.setProp1("default1");        example.setProp2(123);        System.out.println(example.getProp1());        System.out.println(example.getProp2());        marshaller.marshal(example, System.out);        example.setProp1("FOO");        example.setProp2(456);        System.out.println(example.getProp1());        System.out.println(example.getProp2());        marshaller.marshal(example, System.out);    }}

输出量

default1123<?xml version="1.0" encoding="UTF-8" standalone="yes"?><example/>FOO456<?xml version="1.0" encoding="UTF-8" standalone="yes"?><example>    <prop1>FOO</prop1>    <prop2>456</prop2></example>

想要查询更多的信息

  • http://blog.bdoughan.com/2011/06/using-jaxbs-xmlaccessortype-to.html


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

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

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