JAXB:与泛型相关的多态性

我试图用泛型中的JAXB(Jersey内部)来进行多态:

@XmlRootElement
public class Performance<M extends IMeasurement> {

    @XmlAnyElement
    private List<M> measurement;   
}
@XmlJavaTypeAdapter(MeasurementAbstract.Adapter.class)
public interface IMeasurement<D extends Serializable, V extends Number>
        extends Serializable {

    D getDate();    
    void setDate(D date);    
    V getValue();    
    void setValue(V value);
}
@XmlTransient
@XmlAccessorType(XmlAccessType.FIELD)
@XmlSeeAlso({MeasurementStringDouble.class, MeasurementStringInteger.class})
public abstract class MeasurementAbstract<D extends Serializable, V extends Number> implements IMeasurement<D, V> {

    @XmlElement
    protected D date;
    @XmlElement
    protected V value;

    static class Adapter extends XmlAdapter<MeasurementAbstract, IMeasurement> {
        public IMeasurement unmarshal(MeasurementAbstract m) { return m; }
        public MeasurementAbstract marshal(IMeasurement v) { return (MeasurementAbstract) v; }
    }
}
@XmlRootElement
public class MeasurementStringDouble extends MeasurementAbstract<String, Double> {}

@XmlRootElement
public class MeasurementStringInteger extends MeasurementAbstract<String, Integer> {}

我有这个错误:

GRAVE:映射到响应的异常:500(内部服务器错误)javax.ws.rs.WebApplicationException:javax.xml.bind.MarshalException - 带有链接的异常:[javax.xml.bind.JAXBException:class org.test.jaxb.MeasurementStringDouble也没有任何超级类别在这方面是已知的。]


我找到了解决这个问题的解决方案:

@XmlRootElement
public class Performance<M extends IMeasurement> {

    @XmlElementWrapper(name = "measurementsPerformance")
    @XmlElements({
        @XmlElement(name = "measurement", type = MeasurementStringDouble.class),
        @XmlElement(name = "measurement", type = MeasurementStringInteger.class)})
    private List<M> measurement;   
}
public interface IMeasurement<D extends Serializable, V extends Number> extends Serializable {

    D getDate();    
    void setDate(D date);    
    V getValue();    
    void setValue(V value);
}
@XmlTransient
public abstract class MeasurementAbstract<D extends Serializable, V extends Number> implements IMeasurement<D, V>, Serializable {

    protected D date;
    protected V value;
}
@XmlRootElement
@XmlAccessorType(XmlAccessType.PROPERTY)
public class MeasurementStringDouble extends MeasurementAbstract<String, Double> {

    @XmlElement
    @Override
    public String getDate() {
        return date;
    }

    @XmlElement
    @Override
    public Double getValue() {
        return value;
    }
}

@XmlRootElement
@XmlAccessorType(XmlAccessType.PROPERTY)
public class MeasurementStringInteger extends MeasurementAbstract<String, Integer> {

    @XmlElement
    @Override
    public String getDate() {
        return date;
    }

    @XmlElement
    @Override
    public Integer getValue() {
        return value;
    }
}

这个解决方案的缺点是重复子类中的getters / setters。

链接地址: http://www.djcxy.com/p/14665.html

上一篇: JAXB: polymorphism with generics

下一篇: Keep left column visible AND scrollable