2

jaxbの要素のゲッター/セッターペアがあります:

@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メソッドが呼び出されることはないということです。ゲッターとセッターの両方にブレークポイントを設定すると、ゲッターのブレークポイントがヒットしますが、セッターのブレークポイントはヒットしません。

この質問を見つけたばかりですが、答えが完全にはわかりません。myObjectsは構築時に初期化されるため、シナリオ2に適合するように見えます。ゲッターが呼び出された後の非マーシャリングプロセスではどうなりますか?

4

3 に答える 3

3

セッターがゲッターの署名と一致しません。それ以外の:

void setMyObjects(final MyObject... myObjects)

あなたが必要

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

通常、JAXBオブジェクトのリストフィールドにはセッターを使用しません。

代わりに、リストにゲッターを使用して、返されたリストを操作します。

JAXBオブジェクトの例:

class JaxbExample {
    @XmlElement(name="stringList", required = true)
    private List<String> stringList;

    public List<String> getStringList() {
        return stringList;
    }
}

に3つの文字列を追加します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ファイル)からJAXBJavaクラスを生成することがあります。

生成されたクラスにList要素が含まれている場合、Listのsetterメソッドは生成されません。

次のコメントは、各リストのゲッターの上に表示されます。

/**
 * 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

これは、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
}
于 2013-02-20T20:05:50.227 に答える