我有一个 ElectivePolicy 抽象类,它有两个子类 PackagedElectivePolicy 和 SimpleElectivePolicy。为了映射这种继承关系,我使用了 typeAdapter 并且当我检查它时,unmarshal 方法被调用并且运行良好,但是在具有 Elective 策略对象的程序类中,该对象保持为空,你能帮我解决这个问题吗?谢谢
选修政策:
@XmlJavaTypeAdapter(ElectivePolicyAdapter.class)
public abstract class ElectivePolicy {
}
选修政策适配器:
public class ElectivePolicyAdapter extends XmlAdapter<ElectivePolicyAdapter.AdaptedElectivePolicy, ElectivePolicy>{
@Override
public ElectivePolicy unmarshal(AdaptedElectivePolicy adaptedElectivePolicy) throws Exception {
if(adaptedElectivePolicy == null)
return null;
if(adaptedElectivePolicy.packages == null ){
SimpleElectivePolicy sep = new SimpleElectivePolicy();
return sep;
}
else{
PackegedElectivePolicy pep = new PackegedElectivePolicy();
pep.packages = adaptedElectivePolicy.packages;
return pep;
}
}
@Override
public AdaptedElectivePolicy marshal(ElectivePolicy v) throws Exception {
if(v == null)
return null;
AdaptedElectivePolicy adaptedElectivePolicy = new AdaptedElectivePolicy();
if(v instanceof PackegedElectivePolicy){
PackegedElectivePolicy pep = (PackegedElectivePolicy) v;
adaptedElectivePolicy.packages = pep.packages;
}
return adaptedElectivePolicy;
}
public static class AdaptedElectivePolicy{
@XmlElement
ArrayList<Package> packages;
}
}
SimpleElectivePolicy:
public class SimpleElectivePolicy extends ElectivePolicy{
}
PackegedElectivePolicy:
public class PackegedElectivePolicy extends ElectivePolicy {
ArrayList<Package> packages;
public PackegedElectivePolicy(){
packages = new ArrayList<Package>();
}
public ArrayList<Package> getPackages() {
return packages;
}
程序:
@XmlRootElement(name = "program")
@XmlType(propOrder = {"policy" })
public class Program {
@XmlElement(name = "ElectivePolicy")
public ElectivePolicy getPolicy() {
return policy;
}
}