我需要从/向xml文件读取/写入对象。该对象包含一个元素数组。
让我们说Element类看起来如下:
public class Element() {
private BigInteger v;
private BigInteger p;
public Element(BigInteger v, BigInteger p) {...}
public getV() {...}
public getP() {...}
}
MyObject类如下所示:
public class MyObject {
private ArrayList<Element> elements;
public MyObject () {
...
}
@XmlElementWrapper(name="Elements", required=true)
@XmlElement(name="element")
@XmlJavaTypeAdapter(value = ElementAdapter.class, type = Element.class)
public ArrayList<Element> getElements() {
return this.elements;
}
public void setElements(ArrayList<Element> elements) {
this.elements = elements;
}
}
元素构造函数需要2个输入参数(例如Element e = new Element(v, p);
)。但是在MyObject中,所有元素都具有相同的值p
,我想将它存储在文件中一次。这意味着在某些时候我会读取值p
,然后我会读取值v
并使用v
和p
创建元素。
换句话说,我会将MyObject类更改为:
public class MyObject {
private ArrayList<Element> elements;
private BigInteger commonP;
public MyObject(ArrayList<Element> elements) {
this.elements = elements;
this.commonP = elements.get(0).getP();
}
...
@XmlElement(name="P")
public BigInteger getCommonP() {
return this.commonP;
}
public void setCommonP(BigInteger P) {
this.commonP = P;
}
然后我需要以某种方式将commonP
传递给ElementAdapter以创建Element对象。
public class ElementAdapter extends XmlAdapter<BigInteger, Element>{
@Override
public Element unmarshal(BigInteger v) throws Exception {
// Note that commonP does not exist in this scope
return new Element(v, commonP);
}
@Override
public BigInteger marshal(element v) throws Exception {
return v.toBigInteger();
}
}
我的问题是,在解析xml时是否可以设置commonP
并将其传递给ElementAdapter
。