Bean和Map转换的工具类

Bean和Map转换的工具类

依赖包:

基于Spring的cglib 实现。如果是Spring项目,可以不引入依赖。

```
<dependency>
	<groupId>org.springframework</groupId>
	<artifactId>spring-core</artifactId>
	<version>5.3.8</version>
</dependency>
```


工具类如下:

import org.springframework.cglib.beans.BeanMap;
import java.util.HashMap;
import java.util.Map;


public class BeanMapUtil {

    /**
     * 将javaBean对象转换为map
     */
    public static <T> Map<String, Object> beanToMap(T bean) {
        Map<String, Object> map = new HashMap<>();
        if (bean != null) {
            BeanMap beanMap = BeanMap.create(bean);
            for (Object key : beanMap.keySet()) {
                Object value = beanMap.get(key);
                map.put(key + "", value);
            }
        }
        return map;
    }

    /**
     * 将map转换为javaBean对象
     * 注意:map的vaule类型,要与bean对应属性的类型一致
     */
    public static <T> T mapToBean(Map<String, Object> map, T bean) {
        if (map != null) {
            BeanMap beanMap = BeanMap.create(bean);
            beanMap.putAll(map);
        }
        return bean;
    }

}

使用示例:

public void testBeanToMap()  {
    Order order = Order.builder().id(1633376593701060610L).build();
    Map<String, Object> map = BeanMapUtil.beanToMap(order);
    System.out.println(map);
}


public void testMapToBean()  {
    Map<String, Object> map = new HashMap<>();
    //对应Order类的id字段为Long类型
    map.put("id", 12343276L);
    map.put("result", "testTest");
    Order order = new Order();
    BeanMapUtil.mapToBean(map, order);
    System.out.println(order);
} 

参考资料:

https://blog.csdn.net/mybook201314/article/details/118336749
https://www.zhihu.com/question/421708564

posted on 2023-04-26 21:06  乐之者v  阅读(360)  评论(0编辑  收藏  举报

导航