java通过工具类实现对象与map互转

1、导入工具包hutool与lombok依赖

      
            cn.hutool
            hutool-all
            5.7.17
        
        
            org.projectlombok
            lombok
            true
        

2、创建一个测试用实体类

@Data
@ToString
class Student{
    private Long id;
    private String name;
}

3、在测试类中进行测试,测试对象转map,返回结果:对象成功转为map:map为:{id=1, name=可可}

@Test
    public void ObjectToMap(){
       Student student = new Student();
       student.setId(1L);
       student.setName("可可");
        Map map = BeanUtil.beanToMap(student);
        System.out.println("对象成功转为map:map为:"+map);
    }

4、测试map转对象,返回结果为:map成功转为对象:对象为:Student(id=2, name=小花)

  @Test
   public void MapToObject(){
       Map map = new HashMap<>();
       map.put("id","2");
       map.put("name","小花");

       Student student = BeanUtil.fillBeanWithMap(map, new Student(), false);
       System.out.println("map成功转为对象:对象为:"+student);
   }

你可能感兴趣的:(java,java,mybatis,开发语言)