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

例如,下面的代码,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 {

    ...省略
    }
    }

相关推荐
暮色妖娆丶1 小时前
不过是吃了几年互联网红利罢了,我高估了自己
java·后端·面试
NE_STOP2 小时前
MyBatis-参数处理与查询结果映射
java
狂奔小菜鸡2 小时前
Day40 | Java中的ReadWriteLock读写锁
java·后端·java ee
SimonKing4 小时前
JetBrains 用户狂喜!这个 AI 插件让 IDE 原地进化成「智能编码助手」
java·后端·程序员
狂奔小菜鸡4 小时前
Day39 | Java中更灵活的锁ReentrantLock
java·后端·java ee
NE_STOP17 小时前
MyBatis-配置文件解读及MyBatis为何不用编写Mapper接口的实现类
java
后端AI实验室1 天前
用AI写代码,我差点把漏洞发上线:血泪总结的10个教训
java·ai
程序员清风1 天前
小红书二面:Spring Boot的单例模式是如何实现的?
java·后端·面试
belhomme1 天前
(面试题)Redis实现 IP 维度滑动窗口限流实践
java·面试
Be_Better1 天前
学会与虚拟机对话---ASM
java