当我从 XSD 生成 JAXB 类时,带有的元素maxOccurs="unbounded"
获取为它们生成的getter方法,但没有setter方法,如下:
/**
* Gets the value of the element3 property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the element3 property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getElement3().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link Type }
*
*
*/
public List<Type> getElement3() {
if (element3 == null) {
element3 = new ArrayList<Type>();
}
return this.element3;
}
方法注释清楚地说明了如何使用它,但我的问题如下:
为什么 JAXB 不遵循 Java Beans 规则只生成一个 setter?我知道我可以自己编写 setter 方法,但是生成的 getter 方法中建议的方法有什么优点吗?
这是我的 XSD:
<?xml version="1.0" encoding="UTF-8"?>
<schema xmlns="http://www.w3.org/2001/XMLSchema" xmlns:tns="http://www.example.org/DoTransfer/" targetNamespace="http://www.example.org/DoTransfer/">
<element name="CollectionTest" type="tns:CollectionTest"></element>
<complexType name="CollectionTest">
<sequence>
<element name="element1" type="string" maxOccurs="1" minOccurs="1"></element>
<element name="element2" type="boolean" maxOccurs="1" minOccurs="1"></element>
<element name="element3" type="tns:type" maxOccurs="unbounded" minOccurs="1" nillable="true"></element>
</sequence>
</complexType>
<complexType name="type">
<sequence>
<element name="subelement1" type="string" maxOccurs="1" minOccurs="1"></element>
<element name="subelement2" type="string" maxOccurs="1" minOccurs="0"></element>
</sequence>
</complexType>
</schema>
以下是 JAXB 规范 - 第 60 页的理由。
设计说明 – List 属性没有 setter 方法。这
getter 通过引用返回 List。可以将一个项目添加到
getter 方法使用适当的方法返回的列表
定义在 java.util.List 上。JAXB 1.0 中此设计的基本原理是
使实现能够包装列表并能够
在列表中添加或删除内容时执行检查。
因此,如果列表的实现覆盖添加/删除来执行验证,则用(例如)ArrayList 替换该“特殊”列表将导致这些检查失败。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)