简体   繁体   English

如何在JAXB中使用Generics处理Enum?

[英]How to handle Enum with Generics in JAXB?

JAXB runtime is failing to create JAXBContext for a Class whose member variable is defined as JAXB运行时无法为其成员变量定义为的Class创建JAXBContext

@XmlElement(name = "EnumeraatioArvo")
  private Enum<?> eenum;

How to handle such scenario in JAXB? 如何在JAXB中处理这种情况?

I agree with skaffman that this defeats the purpose on enums. 我同意skaffman的说法 ,这会破坏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. 我们需要在eenum属性上使用XmlAdapter。 The XmlAdapter will need to know about all the possible types of Enums that are valid for this property. XmlAdapter需要知道对此属性有效的所有可能类型的枚举。

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验证此方法:

<?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);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM