You are here

JAXB Customizing Generated Java Code

JAXB xjc compiler generates the code when it is passed the schema definition. However sometimes we may want to customize the nature of generated code like:

  • Package names
  • class names
  • Changing enum constants
  • Associating Java types to XML built-in types
  • Documentation

Customization can be added inline to the schema or can be provided in a separate file to the compiler.

Customizing Package Name

package name can be customized in couple of ways:

 

  •  Passing package name to the xjc compiler

   xjc.sh -p <new package name> -d <directory to generate the code> <schema definition>

 

  • Setting inline into the schema defintion file itself

<xsd:annotation>
  <xsd:appinfo>
    <jaxb:schemaBindings>
      <jaxb:package name="com.lalit"/>
    </jaxb:schemaBindings>
  </xsd:appinfo>
</xsd:annotation>

Run the xjc compiler as

xjc.sh  -d <directory to generate the code> <schema definition>

 

  • Writing the customization in a separate file itself

Let's say we write customization.xjb

<?xml version="1.0" encoding="UTF-8"?>
<jaxb:bindings xmlns:jaxb="http://java.sun.com/xml/ns/jaxb" jaxb:version="2.0">
    <jaxb:schemaBindings>
        <jaxb:package name="com.lalit"></jaxb:package>
    </jaxb:schemaBindings>
</jaxb:bindings>

Run the xjc compiler as follows

xjc -b customization.xjb -d <directory to generate the code> <schema definition>

Customizing Names

The class name can be customized to give a different name. Let's change the name of our Address type in xsd

<xsd:complexType name="class">
     <xsd:annotation>
        <xsd:appinfo>
          <jaxb:class name="Address"/>
        </xsd:appinfo>
      </xsd:annotation>    
        <xsd:sequence>
            <xsd:element name="houseNo" type="xsd:string" />
            <xsd:element name="society" type="xsd:string" />
            <xsd:element name="locality" type="xsd:string" />
            <xsd:element name="city" type="xsd:string" />
            <xsd:element name="pin" type="xsd:decimal" />
        </xsd:sequence>
        <xsd:attribute name="country" default="India">
        </xsd:attribute>
    </xsd:complexType>

Now run the xjc compiler keeping and removing the xsd:annotation block.

Add new comment