Sunday, August 17, 2014

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 -p <new package name> -d <directory to generate the code> <schema definition> 

Setting inline into the schema defintion file itself

      <jaxb:package name="com.lalit"/>

Run the xjc compiler as  -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="" jaxb:version="2.0">
        <jaxb:package name="com.lalit"></jaxb:package>

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">
          <jaxb:class name="Address"/>
            <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:attribute name="country" default="India">

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

More on JAXB

No comments:

Post a Comment