我需要从/向 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
,然后我会读取值并使用andv
创建元素。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();
}
}
我的问题是是否可以commonP
在解析 xml 时进行设置并将其传递给ElementAdapter
.