Hutool工具包中BeanUtil的使用

统一声明这里使用得是hutool的BeanUtil,然后在这里主要简单描述了常用的4组API,当然大家可以根据自己的需要去了解对应的方法。

大家可以在pom.xml文件中加入下列语句,即可自动引入相关的jar包。

<!--hutool-->
        <dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-all</artifactId>
            <version>5.7.17</version>
        </dependency>

1、将对象转成map集合,并且在转成map集合的时候可以针对字段转换字段的属性。

beanToMap

可能遇到的问题:使用BeanUtil做beanToMap时,转换字段(可能为null)的属性为String类型。如果不做null判断会出现空指针的错误预警。 大家在这里如果想探究一下原因的话,大家可以参考这一篇博客。 https://blog..net/Qmilumilu/article/details/124476155

Student one = new Student(4,"张三",null,190);
 Map<String, Object> userMap = BeanUtil.beanToMap(one,new HashMap<>(),
                CopyOptions.create().setIgnoreNullValue(true)
                        .setFieldValueEditor((fieldName, fieldValue)->{
          
   
                            if(fieldValue == null){
          
   
                                fieldValue = "0";
                            }else {
          
   
                                fieldValue = fieldValue + "";
                            }
                            return fieldValue;
                        }));

2、将map集合转换成对象: mapToBean

@Test
    /**
     * 将集合转成对象
     */
    void testMapToBean(){
          
   
        Map<String,Object> map = new HashMap<>();
        map.put("id",4);
        map.put("name","张三");
        map.put("age",null);
        map.put("salary",180);
        Student student = BeanUtil.mapToBean(map, Student.class, true, new CopyOptions());
        System.out.println(student);
    }

3、复制对象:copyProperties

在这里大家要注意你所采用的赋值属性的有没有返回值和其中的参数不同,注意查看你传递的是class属性还是新建一个对象。(如果你实体类中有含参数的构造方法,不要忘记了在实体类中的参数为空的构造方法。)

@Test
    /**
     * 复制对象
     */

    void copyBean(){
          
   
        Student two = new Student(4,"李四",18,180);
        CopyOptions copyOptions = new CopyOptions();
        StudentDTO studentDTO = new StudentDTO();
        copyOptions.setIgnoreProperties("id","name");
        BeanUtil.copyProperties(two,studentDTO,copyOptions);
        System.out.println(studentDTO);
    }

4、填充Bean对象:fillBeanWithMap

类似于更新操作,填充值相当于更新值

@Test
    /**
     * 填充对象
     */
    void fillBean(){
          
   
        Student two = new Student(4,"李四",18,180);
        Map<String,Object> map = new HashMap<>();
        map.put("id",5);
        map.put("name","张三");
        map.put("age",null);
        //map.put("salary",194);
        Student student = BeanUtil.fillBeanWithMap(map, two, true);
        System.out.println(student);
    }
经验分享 程序员 微信小程序 职场和发展