0

I need to read/write an object from/to xml file. The object contains an array of elements.

Let's say that Element class looks as follows:

public class Element() {
    private BigInteger v;
    private BigInteger p;

    public Element(BigInteger v, BigInteger p) {...}
    public getV() {...}
    public getP() {...}
}

And MyObject class looks as follows:

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;
    }
}

Element constructor needs 2 input parameters (e.g., Element e = new Element(v, p);). However in MyObject all elements have the same value p and I would like to store it in the file just once. It means that at some point I would read the value p and afterwards I would just read values v and create elements using v and p.

In other words I would change MyObject class to something like this:

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;
    }

Then I need to somehow pass the commonP to ElementAdapter to create Element objects.

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();
    }
}

My question is whether it is possible to set commonP while parsing xml and pass it to ElementAdapter.

Marek Klein
  • 1,410
  • 12
  • 20
  • Is there any reason you can't just add secondParameter later. Do all your unmarshalling first, then add the extra info afterwards? – Joe Dec 09 '16 at 14:10
  • @Joe I can not do that. I am not the author of the library that contains Element and they do not provide setters. So the only way to create an element is to pass both arguments to constructor. I also edited the question, hopefully it is more clear what I'm trying to achieve. – Marek Klein Dec 09 '16 at 15:41

0 Answers0