如何在JAXB中解组工作?

我在jaxb中有一个元素的getter / setter对:

@XmlElementWrapper(name="requires", required=true) @XmlElement(name="equals", required=true) List getMyObjects() { return this.myObject; } void setMyObjects(final MyObject... myObjects) { //call the regular method for setting the objects //that does not have the required signature type } 

问题是setter方法永远不会被调用。 我在getter和setter上放了一个断点,getter的那个被击中,但不是setter的。

我刚刚发现了这个问题 ,但我并不完全理解答案。 myObjects在构造时被初始化,所以看起来它适合场景2.在调用getter之后的解组过程中会发生什么?

你的二传手与你的吸气者的签名不符。 代替:

 void setMyObjects(final MyObject... myObjects) 

你需要

 void setMyObjects(List  myObjects) 

您通常不会在JAXB对象中使用setter作为列表字段。

相反,您使用getter作为列表并使用返回列表的maniuplate。

示例JAXB对象:

 class JaxbExample { @XmlElement(name="stringList", required = true) private List stringList; public List 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 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. * * 

* 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 set method for the stringList property. * *

* For example, to add a new item, do as follows: *

 * getStringList().add(newItem); * 

* * *

* Objects of the following type(s) are allowed in the list * {@link String } * * */

希望这个评论能比我更好地解释!

这实际上并没有解释为什么JAXB以它的方式工作,但我能够让我的代码以我想要的方式工作。 我真的不知道为什么,但这就是我所做的:

 @XmlElementWrapper(name="requires", required=true) @XmlElement(name="equals", required=true) MyObject[] getMyObjects() { //myObjects is an ArrayList return this.myObjects.toArray(EMPTY_OBJECT_ARRAY); } void setMyObjects(final MyObject... myObjects) { //call the regular method for setting the objects //that does not have the required signature type }