为什么JAXB不为列表生成setter [英] Why doesn't JAXB generate setters for Lists
问题描述
当我从XSD生成JAXB类时,带有 maxOccurs =unbounded
的元素会为它们生成一个getter方法,但没有setter方法,如下所示: / p>
When I generate JAXB classes from an XSD, the elements with maxOccurs="unbounded"
gets a getter method generated for them, but no setter method, as follows:
/**
* 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方法中?
The method comment makes it crystal clear on how can I use it, but my question is as follows:
Why doesn't JAXB just generate a setter, following the Java Beans rules? I know I can write the setter method myself, but is there any advantage to the approach suggested in the generated getter method?
这是我的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页。
Here is the justification from the JAXB specification - page 60.
设计注意 - List属性没有setter方法。
getter通过引用返回List。可以使用java.util.List上定义的适当方法
将项添加到getter方法返回的
列表中。 JAXB 1.0中此设计的基本原理是
,以使实现能够包装列表,并且能够在列表中添加或删除内容时执行
执行检查。
因此,如果List的实现覆盖了add / remove来执行验证,那么用(例如)ArrayList替换'special'List会打败这些支票。
So if the implementation of the List was overriding add/remove to perform validation, replacing that 'special' List with (for instance) an ArrayList would defeat these checks.
这篇关于为什么JAXB不为列表生成setter的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!