JAXBElement <boolean> vs boolean </boolean>

时间:2012-10-03 17:06:22

标签: java web-services soap jaxb boolean

JAXBElement Boolean究竟是什么?如何将其设置为“true”的布尔等值?

方法:

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

编译:

returnMessageFilter.setIncludeAllSubaccounts(true); 

2 个答案:

答案 0 :(得分:8)

当JAXB(JSR-222)实现无法仅基于值来判断要执行的操作时,会生成JAXBElement作为模型的一部分。在你的例子中,你可能有一个像:

这样的元素
<xsd:element 
    name="includeAllSubaccounts" type="xsd:boolean" nillable="true" minOccurs="0"/>

生成的属性不能为boolean,因为boolean不代表null。您可以创建属性Boolean,但是如何区分缺少的元素和使用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"), Boolean.class, value);
    }

    @XmlElementDecl(name="setToValue")
    public JAXBElement<Boolean> createSetToValue(Boolean value) {
        return new JAXBElement(new QName("setToValue"), Boolean.class, 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>

答案 1 :(得分:1)

感谢NullUserException的评论,我能够在一行中实现这一点。它略有不同,所以我认为我会发布它以造福他人。

returnMessageFilter.setIncludeAllSubaccounts(new JAXBElement<Boolean>(new QName("IncludeAllSubaccounts"), 
Boolean.TYPE, Boolean.TRUE));

为了澄清,QName是XmlElement标记名。

另外,需要导入:

import javax.xml.bind.JAXBElement;

修改

最好在ObjectFactory类中使用方便方法,该方法返回Blaise建议的JAXBElement