我想使用 JAXB 从 xsd 生成类并使用 xsd 中的默认值。
但是当我将 xs:boolean 元素的默认值设置为“true”时。该值未设置,我收到空指针异常,因为 boolean 对象值尚未初始化为 true。
<xs:element name="statsEnabled" type="xs:boolean" minOccurs="0" default="true"/>
我做错了什么?我们可以只为 xs:string 而不是 xs:boolean 设置默认值吗?
生成的 xml 文件是这样的:
public class Cluster {
@XmlElement(defaultValue = "true")
protected Boolean topoEnabled;
@XmlElement(defaultValue = "true")
protected Boolean statsEnabled;
public Boolean isTopoEnabled() {
return topoEnabled;
}
public Boolean isStatsEnabled() {
return statsEnabled;
}
}
当我尝试调用该函数时:
Cluster cluster = new cluster();
if(cluster.isTopoEnabled)
.....
或者
if(cluster.isStatEnabled)
....
我收到空指针错误。虽然在我的代码中我已经处理了这个空值。
我只是想知道为什么默认值不起作用。我做错了什么,我该怎么办?
或者
是不是默认值只适用于 xs:string 元素而不适用于其他元素?
最佳答案
一种选择是在解码完成后设置该值。
这涉及将以下方法添加到您的对象并在其中设置默认值:
void afterUnmarshal(Unmarshaller u, Object parent) {
this.isStatsEnabled = true;
}
查看相关文档here
关于java - 未在 JAXB 生成的类中设置默认 boolean 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34809474/