java – JAXBElement vs boolean

前端之家收集整理的这篇文章主要介绍了java – JAXBElement vs boolean前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
究竟什么是JAXBElement布尔值,如何将其设置为布尔等效于“true”?

方法

public void setIncludeAllSubaccounts(JAXBElement<Boolean> paramJAXBElement)
  {
    this.includeAllSubaccounts = paramJAXBElement;
  }

这不编译:

returnMessageFilter.setIncludeAllSubaccounts(true);

解决方法

当JAXB(JSR-222)实现无法仅根据值来判断要执行的操作时,JAXBElement将作为模型的一部分生成.在您的示例中,您可能有一个元素,如:
<xsd:element 
    name="includeAllSubaccounts" type="xsd:boolean" nillable="true" minOccurs="0"/>

生成属性不能是布尔值,因为布尔值不表示null.您可以将属性设为布尔值,但是如何区分缺少的元素和使用xsi:nil的元素集.这就是JAXBElement的用武之地.请参阅下面的完整示例:

package forum12713373;

import javax.xml.bind.JAXBElement;
import javax.xml.bind.annotation.*;

@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Foo {

    @XmlElementRef(name="absent")
    JAXBElement<Boolean> absent;

    @XmlElementRef(name="setToNull")
    JAXBElement<Boolean> setToNull;

    @XmlElementRef(name="setToValue")
    JAXBElement<Boolean> setToValue;

}

的ObjectFactory

package forum12713373;

import javax.xml.bind.JAXBElement;
import javax.xml.bind.annotation.*;
import javax.xml.namespace.QName;

@XmlRegistry
public class ObjectFactory {

    @XmlElementDecl(name="absent")
    public JAXBElement<Boolean> createAbsent(Boolean value) {
        return new JAXBElement(new QName("absent"),Boolean.class,value);
    }

    @XmlElementDecl(name="setToNull")
    public JAXBElement<Boolean> createSetToNull(Boolean value) {
        return new JAXBElement(new QName("setToNull"),value);
    }

    @XmlElementDecl(name="setToValue")
    public JAXBElement<Boolean> createSetToValue(Boolean value) {
        return new JAXBElement(new QName("setToValue"),value);
    }

}

演示

package forum12713373;

import javax.xml.bind.*;

public class Demo {

    public static void main(String[] args) throws Exception {
        JAXBContext jc = JAXBContext.newInstance(Foo.class);

        ObjectFactory objectFactory = new ObjectFactory();

        Foo foo = new Foo();
        foo.absent = null;
        foo.setToNull = objectFactory.createSetToNull(null);
        foo.setToValue = objectFactory.createSetToValue(false);

        Marshaller marshaller = jc.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT,true);
        marshaller.marshal(foo,System.out);
    }

}

产量

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<foo>
    <setToNull xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:nil="true"/>
    <setToValue>false</setToValue>
</foo>

猜你在找的Java相关文章