gpt4 book ai didi

java - JAXB:泛型的多态性

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:32:34 29 4
gpt4 key购买 nike

我正在尝试使用 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: Mapped exception to response: 500 (Internal Server Error) javax.ws.rs.WebApplicationException: javax.xml.bind.MarshalException - with linked exception: [javax.xml.bind.JAXBException: class org.test.jaxb.MeasurementStringDouble nor any of its super class is known to this context.]

最佳答案

我找到了解决这个问题的办法:

@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;
}
}

此解决方案的缺点是在子类中重复了 getter/setter。

关于java - JAXB:泛型的多态性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17545149/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com