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";
}
正如我在示例中所示,当我从类方法中删除时,将编组以下 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>
但是当我添加注释时,@XmlTransient
如示例中所示,xml 会根据需要仅使用一个列表进行序列化。
<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>
那么请有人解释一下为什么需要@XmlTransient
在父类getter方法中给出?对于这些情况,继承和 JAXB 如何相互关联?