【发布时间】:2019-09-28 00:01:09
【问题描述】:
我当前的代码完美编组,并且我在生成的 XML 中获得了我想要的元素。即<food>Beef</food>
但是,当我必须将其解组回 java 对象时,问题就出现了。除了食物变量,一切都恢复正常。我最初没有顶部的XmlElement(required = true),并且食物元素总是会解组回null。然后,我添加了 required=true 部分,我遇到了界面问题。我做了一些挖掘,据我所知,jaxb 无法真正解组为接口,因为它不知道要编组的具体类型。
如果有帮助,当前错误:
Can not set FoodInterface field BigPayload.food to
com.sun.org.apache.xerces.internal.dom.ElementNSImpl
我的Java类如下:
@XmlSeeAlso({MeatFoods.class, VeggieFoods.class})
@XmlType(name ="BigPayload", propOrder = //stuff goes here
@XmlRootElement(name = foodPayload)
public class BigPayload implements Payload{
@XmlElements({@XmlElement(type = MeatFoods.class),
@XmlElement(type = VeggieFoods.class),
@XmlElement(required = true)})
protected FoodInterface food;
protected Grade grade;
//grade/food setters and getters
}
@XmlTransient //If this isn't here, I get the jaxB cannot handle interfaces and no default constructor error
public interface FoodInterface{ //stuff here}
@XmlType(name = "MeatFoods")
@XmlEnum
public enum MeatFoods implements FoodInterface{
Chicken(1, Chicken)
Beef(2, Beef)
Pork(3, Pork)
int value;
String name;
@Override
public int getValue()
@Override
public String getName()
public static FoodInterface getEnumFromValue(int value){//gets stuff}
public static FoodInterface getEnumFromName(String name){//gets stuff}
}
我只是想知道这是否正确,并且没有真正好的方法来解组接口类型。这是真的?我看到很多其他问题是关于编组接口的,而解组问题并没有真正得到令我满意的答案。任何答案都值得赞赏,我知道这不是一个最小的可重复示例,但我更多的是寻找口头答案而不是代码修复或任何东西。不过,如果代码中有任何明显错误,请告诉我!
【问题讨论】:
-
是的——这是可能的。我在接口类型的字段上使用@XmlElements,它成功地编组和解组。
标签: java interface jaxb marshalling unmarshalling