JAXB objects initialized with default values

前端 未结 2 1420
太阳男子
太阳男子 2020-12-11 02:58

There is little problem with JAXB.


Given:

  • Java 1.5; jaxb -jars from jaxws-2_0.
  • .xsd scheme and genera
相关标签:
2条回答
  • 2020-12-11 03:26

    For an initialization of the class members from XSD supplied defaults, you can use the default-value-plugin of XJC.

    See the website of the plugin.

    Note that the ant task definition as explained in that documentation did not work for me. As explained here, the class paths for XJC and the plugin have to be separated. Specifying the path to the plugin when calling it works for me:

    <xjc schema="some.xsd" >
        <arg value="-Xdefault-value"/>
        <classpath>
            <pathelement location="lib/xjc-plugins/jaxb2-default-value-1.1.jar"/>
        </classpath>
    </xjc>
    
    0 讨论(0)
  • 2020-12-11 03:38

    default value that is in annotations works only after unmarshalling.
    unmarshal this

    <document>
       <d_int/>
       <d_double/>
       <d_string/>
    </document>  
    

    and you will get object with default values (-1, -1.0, "Default")

    If you want set default values to marshalling, you should do this

    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";
    ...
    }    
    

    jaxb generate default values only for unmarshalling

    0 讨论(0)
提交回复
热议问题