使用默认值初始化JAXB对象

A7i*_*7iz 10 xsd jaxb default-value

JAXB几乎没有问题.


鉴于:

  • Java 1.5; 来自jaxws-2_0的jaxb -jars.
  • .xsd方案和生成的JAXB类.
  • .xsd中的每个简单元素都有默认值.因此,类成员的注释类似于" @XmlElement(name ="cl_fname",required = true,defaultValue ="[ _ __ _ __]") "

需要


获取完全代表xml的java对象(根元素)以及默认值初始化的每个成员.


当我尝试在没有显式设置值的情况下编组xml时,默认值不会出现...是否有任何方法可以使用默认值编组xml而无需自定义生成的类?

.xsd的示例:

<xs:element name="document">
    <xs:complexType>
        <xs:sequence>
            <xs:element ref="d_int"/>
            <xs:element ref="d_double"/>
            <xs:element ref="d_string"/>
        </xs:sequence>
    </xs:complexType>
</xs:element>

<xs:element name="d_int" type="xs:int" default="-1"/>
<xs:element name="d_double" type="xs:double" default="-1.0"/>
<xs:element name="d_string" type="xs:string" default="false"/>
Run Code Online (Sandbox Code Playgroud)

和java类:

public class Document {
    @XmlElement(name = "d_int", defaultValue = "-1")
    protected int dInt;
    @XmlElement(name = "d_double", defaultValue = "-1.0")
    protected double dDouble;
    @XmlElement(name = "d_string", required = true, defaultValue = "Default")
    protected String dString;
...
}
Run Code Online (Sandbox Code Playgroud)

Ily*_*lya 19

注释中的默认值仅在解组后才起作用.
解散这个

<document>
   <d_int/>
   <d_double/>
   <d_string/>
</document>  
Run Code Online (Sandbox Code Playgroud)

并且您将获得具有默认值的对象(-1,-1.0,"默认")

如果要将默认值设置为编组,则应执行此操作

public class Document {
    @XmlElement(name = "d_int", defaultValue = "-1")
    protected int dInt = 100;
    @XmlElement(name = "d_double", defaultValue = "-1.0")
    protected double dDouble = -100;
    @XmlElement(name = "d_string", required = true, defaultValue = "Default")
    protected String dString = "def";
...
}    
Run Code Online (Sandbox Code Playgroud)

jaxb仅为解组生成默认值

  • 我一直在想,如果您还指定了一个 `defaultValue`,那么将字段标记为 `required` 是否有任何意义。这似乎自相矛盾,不是吗? (2认同)