gpt4 book ai didi

java - 为什么 JAXB 不为列表生成 setter

转载 作者:IT老高 更新时间:2023-10-28 20:25:32 26 4
gpt4 key购买 nike

当我从 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 不只是生成一个 setter,遵循 Java Beans 规则? 我知道我可以自己编写 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 页。

Design Note – There is no setter method for a List property. The getter returns the List by reference. An item can be added to the List returned by the getter method using an appropriate method defined on java.util.List. Rationale for this design in JAXB 1.0 was to enable the implementation to wrapper the list and be able to perform checks as content was added or removed from the List.

因此,如果 List 的实现覆盖了 add/remove 以执行验证,那么用(例如)ArrayList 替换那个“特殊”的 List 会破坏这些检查。

关于java - 为什么 JAXB 不为列表生成 setter ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13913000/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com