开发者

How to handle Enum with Generics in JAXB?

JAXB runtime is failing to create JAXBContext for a Class whose member variable is defined as

@XmlElement(name开发者_开发技巧 = "EnumeraatioArvo")
  private Enum<?> eenum;

How to handle such scenario in JAXB?


I agree with skaffman that this defeats the purpose on enums. If for some reason this is something you need to do, you could try the following:

import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;

@XmlRootElement
public class Root {

    private Enum<?> eenum;

    @XmlJavaTypeAdapter(EnumAdapter.class)
    public Enum<?> getEenum() {
        return eenum;
    } 

    public void setEenum(Enum<?> eenum) {
        this.eenum = eenum;
    }

}

Below are two sample Enums we will use in this example:

public enum Compass {
    NORTH, SOUTH, EAST, WEST
}

public enum Suit {
    CLUBS, SPADES, DIAMONDS, HEARTS
}

We need to use an XmlAdapter on the eenum property. The XmlAdapter will need to know about all the possible types of Enums that are valid for this property.

import javax.xml.bind.annotation.adapters.XmlAdapter;

public class EnumAdapter extends XmlAdapter<String, Enum> {

    private Class[] enumClasses = {Compass.class, Suit.class};

    @Override
    public Enum unmarshal(String v) throws Exception {
        for(Class enumClass : enumClasses) {
            try {
                return (Enum) Enum.valueOf(enumClass, v);
            } catch(IllegalArgumentException  e) {
            }
        }
        return null;
    }

    @Override
    public String marshal(Enum v) throws Exception {
        return v.toString();
    }

}

You can verify this works with the following XML:

<?xml version="1.0" encoding="UTF-8"?>
<root>
    <eenum>SPADES</eenum>
</root>

By using the following code:

import java.io.File;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

public class Demo {

    public static void main(String[] args) throws Exception {
        JAXBContext jc = JAXBContext.newInstance(Root.class);

        Unmarshaller unmarshaller = jc.createUnmarshaller();
        File xml = new File("input.xml");
        Root root = (Root) unmarshaller.unmarshal(xml);

        Marshaller marshaller = jc.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.marshal(root, System.out);
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜