首页 > 解决方案 > 通过迭代将 object[] 转换为实体类型

问题描述

我有一个类型的 pojo

 public class Comain implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)

    private Integer ComainId;

    private String name;

    private String Cescription;


     private boolean  isAvailable ;
     }

下面是我提取结果的一段代码

   List<Object[]>  d = new ArrayList<Object[]>();
   d = ARepository.getAb();

调试后我分析我得到以下格式的结果

 d = {ArrayList}
    > o = {object[4]}
       > o = {Integer}1
       > 1 = "qqq"
       > 2 = "ddddd"
       > 3 = {Boolean} false
     > 1 = {object[4]}
       > o = {Integer}2
       > 1 = "qrtq"
       > 2 = "rrddd"
       > 3 = {Boolean} true

现在我想将 object[] 数组类型转换为 Comain pojo 的 pojo 类型,尽管我已经创建了对象类型 Comain,但请告知如何实现相同的目标

   Comain C = new Comain ()

调试图像

标签: java

解决方案


如果对象数组的顺序是固定的,那么您可以遍历数组并使用相应的索引。

List<Comain> comains = new ArrayList<>();
for (Object[] objects : d) {
    comains.add(new Comain((Integer) objects[0], (String) objects[1], (String) objects[2], (Boolean) objects[3]));
}

当然,您必须为Comain该类添加一个构造函数。

public Comain(Integer comainId, String name, String cescription, boolean isAvailable) {
    this.ComainId = comainId;
    this.name = name;
    this.Cescription = cescription;
    this.isAvailable = isAvailable;
}

推荐阅读