6

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

方法:

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

这不会编译

returnMessageFilter.setIncludeAllSubaccounts(true); 
4

2 回答 2

8

JAXBElement当 JAXB (JSR-222) 实现无法仅根据值判断要做什么时,A会作为模型的一部分生成。在您的示例中,您可能有一个元素,例如:

<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;

}

对象工厂

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>
于 2012-10-03T19:13:28.173 回答
1

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

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

澄清一下,QName 是 XmlElement 标记名称。

另外,需要导入:

import javax.xml.bind.JAXBElement;

编辑

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

于 2012-10-04T17:40:03.127 回答