java – The magic of marshalling with JAXB

Question:

@XmlRootElement(name = "graph")
@XmlAccessorType(XmlAccessType.NONE)
public class Class1 {

public List<Integer> i1;

public Class1(Integer... i1) {
    if (this.i1 == null) {
        this.i1 = new ArrayList<>();
    }
    for (Integer Int : i1) {
        this.i1.add(Int);
    }
}

public Class1() {
}

@XmlElement
public List<Integer> getI1() {
    return i1;
}

public void setI1(List<Integer> i1) {
    if (this.i1 == null) {
        this.i1 = new ArrayList<>();
    }

    System.out.println("before: " + this.i1);
    this.i1 = i1.stream().map(arg -> arg*2).collect(Collectors.toList());
    System.out.println("after: " + this.i1);

}

@Override
public String toString() {
    return "Class1{" +
            "i1=" + i1 +
            '}';
}
}

Omitting JAXB initialization. Here is what class we will marshall, and then unmarshall (I omit the details): new Class1 (1,2,3)

result :

before: [ ] 
after: [ ] 
Class1{i1=[ ]}

replace the setter with:

    public void setI1(List<Integer> i1) {
    if (this.i1 == null) {
        this.i1 = new ArrayList<>();
    }

    System.out.println("before: " + this.i1);
    this.i1 = i1;
    System.out.println("after: " + this.i1);

}

result:

before: [ ] 
after: [ ] 
Class1{i1=[1, 2, 3]}

The question is, what is this hellish magic? And is it possible to somehow process the values ​​coming to the setter / getter?

Answer:

When the setter is called, an empty list that JAXB created is passed into it. And you see this after: [ ] . But then JAXB starts filling this list with elements. But since In the first case, you create a new list, the filled list simply disappears somewhere in the depths of JAXB, in the second case, you save the link to the list, which will then be filled and as a result you see Class1{i1=[1, 2, 3]}

Scroll to Top