gpt4 book ai didi

java - JAXBElement 与 boolean 值

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:03:01 25 4
gpt4 key购买 nike

JAXBElement Boolean 到底是什么?我如何将其设置为与“true”等效的 boolean 值?

方法:

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

编译:

returnMessageFilter.setIncludeAllSubaccounts(true); 

最佳答案

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

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

关于java - JAXBElement<Boolean> 与 boolean 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12713373/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com