2

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

@XmlElementWrapper(name="requires", required=true) 
@XmlElement(name="equals", required=true)
List<MyObject> 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 之后的解组过程中会发生什么?

4

3 回答 3

3

您的 setter 与您的 getter 的签名不匹配。代替:

void setMyObjects(final MyObject... myObjects)

你需要

void setMyObjects(List <MyObject> myObjects)
于 2013-02-20T18:06:11.950 回答
2

您通常不会将 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 }
 * 
 * 
 */

希望该评论在解释方面比我做得更好!

于 2013-02-20T20:09:35.637 回答
2

This doesn't actually explain why JAXB works the way it does, but I was able to get my code to work the way I wanted it to. I don't really know why, but this is what I did:

@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
}
于 2013-02-20T20:05:50.227 回答