In XML Schema, enumerated types are simple types that are defined using the
xsd:enumeration
facet. Unlike atomic simple types, they are mapped to Java
enums.
Enumerations are a simple type using the xsd:enumeration
facet. Each
xsd:enumeration
facet defines one possible value for the enumerated type.
Example 12.5 shows the definition for an enumerated type. It has the following possible values:
big
large
mungo
gargantuan
Example 12.5. XML Schema Defined Enumeration
<simpleType name="widgetSize"> <restriction base="xsd:string"> <enumeration value="big"/> <enumeration value="large"/> <enumeration value="mungo"/> <enumeration value="gargantuan"/> </restriction>
XML Schema enumerations where the base type is xsd:string are automatically mapped to Java enum type. You can instruct the code generator to map enumerations with other base types to Java enum types by using the customizations described in Customizing Enumeration Mapping.
The enum type is created as follows:
The name of the type is taken from the name
attribute of the simple type definition and
converted to a Java identifier.
In general, this means converting the first character of the XML Schema's name to an uppercase letter. If the first
character of the XML Schema's name is an invalid character, an underscrore (_
) is prepended to the
name.
For each enumeration
facet, an enum constant is generated based on the value of the
value
attribute.
The constant's name is derived by converting all of the lowercase letters in the value to their uppercase equivalent.
A constructor is generated that takes the Java type mapped from the enumeration's base type.
A public method called value()
is generated to access the facet value that is represented
by an instance of the type.
The return type of the value()
method is the base type of the XML Schema type.
A public method called fromValue()
is generated to create an instance of the enum type
based on a facet value.
The parameter type of the value()
method is the base type of the XML Schema
type.
The class is decorated with the @XmlEnum
annotation.
The enumerated type defined in Example 12.5 is mapped to the enum type shown in Example 12.6.
Example 12.6. Generated Enumerated Type for a String Bases XML Schema Enumeration
@XmlType(name = "widgetSize") @XmlEnum public enum WidgetSize { @XmlEnumValue("big") BIG("big"), @XmlEnumValue("large") LARGE("large"), @XmlEnumValue("mungo") MUNGO("mungo"), @XmlEnumValue("gargantuan") GARGANTUAN("gargantuan"); private final String value; WidgetSize(String v) { value = v; } public String value() { return value; } public static WidgetSize fromValue(String v) { for (WidgetSize c: WidgetSize.values()) { if (c.value.equals(v)) { return c; } } throw new IllegalArgumentException(v); } }