prev table of contents next

2.2 JAXB Examples

This chapter discusses various XML Schema constructs and how they are bound by the JAXB schema compiler xjc. For brevity and clarity, the resulting Java code is generally shown without the annotations.

2.2.1 Defining an Integer Range Type

The XML Schema snippet shown below defines an integer type, limiting permissible values to the range 1 to 255.

<xsd:simpleType name="GroupType">
  <xsd:restriction base="xsd:int">
    <xsd:minInclusive value="1"/>
    <xsd:maxInclusive value="255"/>
  </xsd:restriction>
</xsd:simpleType>
A simple type restricting xsd:int will not result in a separate Java class being generated. The JAXB compiler will simply fall back to int (or Integer) in all the places where GroupType is used.

If you peek into one of these class definitions, you'll see simple get and set methods, like in this class derived from a schema type where an element has an attribute with name Group and type GroupType:

public class ElementType {
    // ...
    @XmlAttribute(name = "Group", required = true)
    protected int group;
    // ...
    public int getGroup() {
        return group;
    }
    public void setGroup(int value) {
        this.group = value;
    }
    // ...
}
Where is, you might ask, the code that ensures that the integer value is between the bounds? The short and, perhaps, disappointing anwer is that there is no such code. JAXB expects you to request detailed validation explicitly by passing a javax.xml.validation.Schema object, created from your XML schema, to the marshaller or unmarshaller used for handling your data. We'll discuss this in the section on
Validation.


prev table of contents next