您通常不会将 setter 用于 JAXB 对象中的列表字段。
相反,您将 getter 用于列表并操作返回的列表。
示例 JAXB 对象:
class JaxbExample {
@XmlElement(name="stringList", required = true)
private List<String> stringList;
public List<String> getStringList() {
return stringList;
}
}
将三个字符串添加到stringList
:
JaxbExample someObject = ...;
// add three Strings to stringList
someObject.getStringList().add("foo");
someObject.getStringList().add("bar");
someObject.getStringList().add("baz");
// now the list contains 3 new strings and there was
// no need to use a setter.
将 stringList 设置为现有列表:
JaxbExample someObject = ...;
List<String> someList = ...;
// set someObject's stringList to someList
someObject.getStringList().addAll(someList);
为了进一步澄清...
我们有时使用XJC 实用程序从 XML 模式文件(.XSD 文件)生成 JAXB Java 类。
当生成的类包含 List 元素时,不会为 List 生成 setter 方法。
以下注释出现在每个 List 的 getter 上方:
/**
* Gets the value of the stringList 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 stringList property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getStringList().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link String }
*
*
*/
希望该评论在解释方面比我做得更好!