@XmlAttribute/@XmlValue 需要引用映射到 XML 中的文本的 Java 类型

@XmlAttribute/@XmlValue need to reference a Java type that maps to text in XML

如何选择属性 'name' 的值,在下面的例子中,它是一个 PriceEventName class 类型,仅供参考,如果我将 @XmlAttribute 放在它上面,这将导致异常 "an error @XmlAttribute/@XmlValue need to reference a Java type that maps to text in XML" 我在互联网上大量查找,但没有找到与我的情况类似的内容

PriceEvent class

package somepackage
import ...
import 
@XmlAccessorType(XmlAccessType.FIELD)

    public class PriceEvent {
        @XmlElement(name="Message",namespace="someValue")
        private String color;

        private PriceEventName name;// this is an attribute 
        .
        .
    }

价格事件名称class

Imports ...

public class PriceEventName {

    public static final int PRICEUPDATE_TYPE = 0;
    public static final PriceEventName PRICEUPDATE = new PriceEventName(PRICEUPDATE_TYPE, "X-mas");
    private static java.util.Hashtable _memberTable = init();
    private static java.util.Hashtable init() {
        Hashtable members = new Hashtable();
        members.put("X-mas", PRICEUPDATE);
        return members;
    }

    private final int type;
    private java.lang.String stringValue = null;

        public PriceEventName(final int type, final java.lang.String value) {
        this.type = type;
        this.stringValue = value;
    }

    public static PriceEventName valueOf(final java.lang.String string) {
        java.lang.Object obj = null;
        if (string != null) {
            obj = _memberTable.get(string);
        }
        if (obj == null) {
            String err = "" + string + " is not a valid PriceEventName";
            throw new IllegalArgumentException(err);
        }
        return (PriceEventName) obj;
        }
}

这是使用适配器将字段声明为属性的方式:

@XmlJavaTypeAdapter(PenAdapter.class)
@XmlAttribute 
protected PriceEventName name;
public PriceEventName getName() { return name; }
public void setName(PriceEventName value) { this.name = value; }

添加您需要将 getter 添加到 PriceEventName:

public String getStringValue(){ return stringValue; }

这是适配器 class:

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

public class PenAdapter extends XmlAdapter<String,PriceEventName> {
    public PriceEventName unmarshal(String v) throws Exception {
        return PriceEventName.valueOf( v );
    }
    public String marshal(PriceEventName v) throws Exception {
        return v.getStringValue();
    }
}