继承和 JAXB 如何协同工作?
2022-09-04 03:59:46
public abstract class Parent<T> {
protected List<T> list;
@XmlTransient //Question why do we have to give this here?
public abstract List<T> getList();
public abstract void setList(List<T> list);
}
@XmlRootElement(name = "child1")
class Child1 extends Parent<ExtendedElement1>{
@Override
public void setList(List<ExtendedElement1> list){
this.list = list;
}
@Override
@XmlElementWrapper(name = "child1-list")
@XmlElement(name = "child-list-element")
public List<ExtendedElement1> getList(){
return this.list;
}
}
@XmlRootElement(name = "child2")
class Child2 extends Parent<ExtendedElement2>{
@Override
public void setList(List<ExtendedElement2> list){
this.list = list;
}
@Override
@XmlElementWrapper(name = "child1-list")
@XmlElement(name = "child-list-element")
public List<ExtendedElement2> getList(){
return this.list;
}
}
class Element{
@XmlElement(name = "integer", type = int.class)
private int i = 2;
}
class ExtendedElement1 extends Element{
@XmlElement(name = "extended-element1-str", type = String.class)
private String str = "hello";
}
class ExtendedElement2 extends Element{
@XmlElement(name = "extended-element2-str", type = String.class)
private String str1 = "hello_there";
}
正如我在示例中演示的那样,当我删除 from the class 方法时,以下 xml 被封送:@XmlTransient
Parent
getList()
<child1>
<!-- List is serialized 2 times -->
<list xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="extendedElement1">
<integer>2</integer>
<extended-element1-str>hello</extended-element1-str>
</list>
<list xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="extendedElement1">
<integer>2</integer>
<extended-element1-str>hello</extended-element1-str>
</list>
<list xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="extendedElement1">
<integer>2</integer>
<extended-element1-str>hello</extended-element1-str>
</list>
<child1-list>
<child-list-element>
<integer>2</integer>
<extended-element1-str>hello</extended-element1-str>
</child-list-element>
<child-list-element>
<integer>2</integer>
<extended-element1-str>hello</extended-element1-str>
</child-list-element>
<child-list-element>
<integer>2</integer>
<extended-element1-str>hello</extended-element1-str>
</child-list-element>
</child1-list>
</child1>
但是,当我添加注释时,如示例中所示,xml 被序列化,仅在需要时使用一个列表。@XmlTransient
<child1>
<child1-list>
<child-list-element>
<integer>2</integer>
<extended-element1-str>hello</extended-element1-str>
</child-list-element>
<child-list-element>
<integer>2</integer>
<extended-element1-str>hello</extended-element1-str>
</child-list-element>
<child-list-element>
<integer>2</integer>
<extended-element1-str>hello</extended-element1-str>
</child-list-element>
</child1-list>
</child1>
所以请有人解释一下为什么需要在父类getter方法中给出?在这些情况下,继承和 JAXB 如何相互关联?@XmlTransient