我有一个扩展ParentClass的类(ChildClass)。在解组时,我从setPropFromElementList()获得一个异常,即我传入的值在列表中不存在,即使它确实存在于列表中。我认为问题是由JAXB在设置子元素之前尝试设置父元素的属性引起的。
我看到了各种博客帖子和问题,建议将父类设为Transient,然后在子类上使用propOrder(包括父类中的元素)。这对我没有帮助 - 我收到了IllegalAnnotationException。
有什么想法吗? (示例代码如下 - 它不是我使用的完全代码,所以我不是100%肯定它会编译。但它确实显示了我在实际代码中所做的。)< / p>
ParentClass.java
@XmlTransient //on the entire class - not shown here
private String propFromElementList
@XmlAttribute
String getPropFromElementList() {
return this.propFromElementList;
}
void setPropFromElementList(String value) {
checkThatValueIsInList(value);
this.propFromElementList = value;
}
protected abstract void checkThatValueIsInList(String value);
ChildClass.java扩展了ParentClass
@XmlType(propOrder = {“list”,“propFromElementList”})
private String[] list;
@XmlElement
public String[] getList() {
return this.list;
}
public void setList(final String... list) {
this.list = list;
}
@Override
protected void checkThatValueIsInList(String value) {
//search for String and throw RuntimeException if not found
}
XML
<child propFromElementList="A">
<list>A B C D</list>
</child>
答案 0 :(得分:0)
<强>更新强>
有没有办法确保在使用继承时在属性之前设置我的jaxb元素?
您无法控制JAXB (JSR-222)实施填充域模型的顺序。 JAXB impl最喜欢填充对象模型,因为它在unmarshal操作期间执行XML文档的深度优先遍历。这意味着通常会在任何子元素之前处理属性,这些子元素似乎是导致用例出现问题的原因。
您可能需要考虑将验证逻辑移到setPropFromElementList
方法之外,并将其放在afterUnmarshal
方法中。
原始回答
propOrder
上的@XmlType
设置仅在编组时使用。您不能在propOrder
@XmlType
上包含使用@XmlAttribute映射的属性。既然你有:
@XmlAttribute
String getPropFromElementList() {
return this.propFromElementList;
}
然后propFromElementList
无法出现在仅适用于非属性节点的propOrder
中。