prev table of contents next

6.2.7 Annotations for Fields

Fields of a class may correspond to XML elements. Once more, there is a gap between what can be defined in an XML schema and the information available from field definitions within a Java class.

6.2.7.1 The Annotation XmlElement

The basic annotation for a field that's intended to be an element is XmlElement. It permits you to define the XML element name, the namespace, whether it is optional or nillable, a default value and the Java class. Here are two annotated fields, and below is the corresponding schema snippet.

@XmlElement(name = "Preamble", required = true)
protected PreambleType preamble;
@XmlElement(name = "Workplace", required = true)
protected List<SysWorkplaceType> workplace;
<xsd:sequence>
  <xsd:element name="Preamble"  type="com:PreambleType"/>
  <xsd:element name="Workplace" type="SysWorkplaceType"
               minOccurs="1" maxOccurs="unbounded"/>
</xsd:sequence>

If a field has some collection type, more than one @XmlElement may have to be associated with this field. This requires that these annotations are assembled in a XmlElements (note the plural "s") annotation that merely acts as a container. In the class definition below, the field entryOrChoiceOrCascade is a collection composed from objects of three different classes.

@XmlType(name = "MenuType")
public class MenuType extends ItemType {

    @XmlElements({
        @XmlElement(name = "Item",     type = ItemType.class),
        @XmlElement(name = "CheckBox", type = CheckBoxType.class),
        @XmlElement(name = "Menu",     type = MenuType.class)
    })
    protected List entryList;
}
As a bonus you may avoid the complicated name for the list element that JAXB concocts from the first three possibles.


prev table of contents next