Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JAXB element of type enum

So I know how to create an enum type but when I set an element type to it the element field will just be of type string and not of type enum. How do I create an enum in my schema and have JAXB generate it as a java enum type?

This is how I'm doing my enum type and element creation:

<xsd:simpleType name="myEnum">
    <xsd:restriction base="xsd:string">
        <xsd:enumeration value="MY_ENUM_1"/>
        <xsd:enumeration value="MY_ENUM_2"/>
    </xsd:restriction>
</xsd:simpleType>

<xsd:element name="myEnumElement" type="ns1:myEnum"/>
like image 727
Nikordaris Avatar asked Apr 27 '11 15:04

Nikordaris


2 Answers

You could form your XML schema as follows:

<?xml version="1.0" encoding="UTF-8"?>
<xsd:schema targetNamespace="http://www.example.com" xmlns="http://www.example.com" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <xsd:simpleType name="myEnum">
        <xsd:restriction base="xsd:string">
            <xsd:enumeration value="MY_ENUM_1"/>
            <xsd:enumeration value="MY_ENUM_2"/>
        </xsd:restriction>
    </xsd:simpleType>
    <xsd:element name="root">
        <xsd:complexType>
            <xsd:sequence>
                <xsd:element name="local" type="myEnum"/>
                <xsd:element name="ref" type="myEnum"/>
            </xsd:sequence>
        </xsd:complexType>
    </xsd:element>
</xsd:schema>

Will cause the following Enum to be generated:

package com.example;

import javax.xml.bind.annotation.*;

@XmlType(name = "myEnum")
@XmlEnum
public enum MyEnum {

    MY_ENUM_1,
    MY_ENUM_2;

    public String value() {
        return name();
    }

    public static MyEnum fromValue(String v) {
        return valueOf(v);
    }

}

And the following class that leverages that Enum:

package com.example;

import javax.xml.bind.annotation.*;

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
    "local",
    "ref"
})
@XmlRootElement(name = "root")
public class Root {

    @XmlElement(required = true)
    protected MyEnum local;
    @XmlElement(required = true)
    protected MyEnum ref;

    public MyEnum getLocal() {
        return local;
    }

    public void setLocal(MyEnum value) {
        this.local = value;
    }

    public MyEnum getRef() {
        return ref;
    }

    public void setRef(MyEnum value) {
        this.ref = value;
    }

}

For More Information

  • http://blog.bdoughan.com/2011/08/jaxb-and-enums.html
like image 80
bdoughan Avatar answered Oct 18 '22 13:10

bdoughan


See jaxb:globalBindings/@typeSafeEnumBase here.

like image 35
lexicore Avatar answered Oct 18 '22 13:10

lexicore