XmlElement注解在Java列表属性:要注意实例化,否则从xml数据反序列化到Java对象会失败

文章讲述了Java类Conditions中,如何处理conditionList属性的实例化问题,特别是在XML反序列化时,确保其非空以避免错误。提到了在get方法中进行初始化和在类声明时初始化两种情况。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

例如,下面的代码,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 {
...省略
     }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值