例如,下面的代码,Java类Conditions的属性conditionList是一个列表类型。XmlRootElement注解在conditionList的get方法上(等同于注解在属性上)。需要注意该属性的实例化,如果不实例化的话,从xml数据反序列化到Java对象的时候出错。
可以在两个地方实例化:
-
在 get方法中,首先判断conditionList是否为null,如果为null的话,则实例化:
package com.thb.platform;
import java.util.ArrayList;
import java.util.List;import jakarta.xml.bind.annotation.XmlAttribute;
import jakarta.xml.bind.annotation.XmlElement;
import jakarta.xml.bind.annotation.XmlRootElement;
import jakarta.xml.bind.annotation.XmlType;
import jakarta.xml.bind.annotation.XmlValue;@XmlRootElement(name = "conditions")
@XmlType(propOrder = {"identify", "table", "conditionList", "total", "pageSize", "pageNo"})
public class Conditions {
...省略
private List<Conditions.Condition> conditionList;@XmlElement(name = "condition") public List<Conditions.Condition> getconditionList(){ if (conditionList == null) { conditionList = new ArrayList<>(); } return this.conditionList; } public void setCondition( List<Conditions.Condition> conditionList) { this.conditionList = conditionList; }
...省略
@XmlType(propOrder = {"value"}) public static class Condition {
...省略
}
} -
在声明属性conditionList的时候实例化:
package com.thb.platform;
import java.util.ArrayList;
import java.util.List;import jakarta.xml.bind.annotation.XmlAttribute;
import jakarta.xml.bind.annotation.XmlElement;
import jakarta.xml.bind.annotation.XmlRootElement;
import jakarta.xml.bind.annotation.XmlType;
import jakarta.xml.bind.annotation.XmlValue;@XmlRootElement(name = "conditions")
@XmlType(propOrder = {"identify", "table", "conditionList", "total", "pageSize", "pageNo"})
public class Conditions {
...省略private List<Conditions.Condition> conditionList = new ArrayList<>(); @XmlElement(name = "condition") public List<Conditions.Condition> getconditionList(){ return this.conditionList; } public void setCondition( List<Conditions.Condition> conditionList) { this.conditionList = conditionList; }
...省略
@XmlType(propOrder = {"value"}) public static class Condition {
...省略
}
}