java工具类-bean转map

工作常常遇到将java的Bean对象转化为Map,或者将Map转为Bean对象。

常见的手段

  • 通过json工具,将Bean转json,再将json转Map

    效率低

  • jdk的反射,获取类的属性,进行转化

    比较麻烦,书写代码比较多

  • 通过工具类BeanMap来完成

    效率高,底层也是基于反射,不过做了些优化,比如缓存等手段 (推荐)

  • 通过Apache的BeanUtils来完成

    bean转化map是Map<String, String>类型

循环转化1w次,对比下BeanMap和BeanUtils的耗时(毫秒)

方式bean转mapmap转bean
BeanMap593364
BeanUtils12542430

由上测试结果,我们可以看出BeanMap效率高,所以推荐使用BeanMap

更多内容可以关注:iworkh博客

1.BeanMap方式

BeanMap是org.springframework.cglib.beans.BeanMap,在springcore中

1-1.工具类BeanMapTool

package com.iworkh.test.restassured.utils;

import org.springframework.cglib.beans.BeanMap;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * bean和map互转
 *
 * @author: iworkh-沐雨云楼
 * @date: 2020-06-18
 */
public class BeanMapTool {

    public static <T> Map<String, ?> beanToMap(T bean) {
        BeanMap beanMap = BeanMap.create(bean);
        Map<String, Object> map = new HashMap<>();

        beanMap.forEach((key, value) -> {
            map.put(String.valueOf(key), value);
        });
        return map;
    }

    public static <T> T mapToBean(Map<String, ?> map, Class<T> clazz)
            throws IllegalAccessException, InstantiationException {
        T bean = clazz.newInstance();
        BeanMap beanMap = BeanMap.create(bean);
        beanMap.putAll(map);
        return bean;
    }

    public static <T> List<Map<String, ?>> objectsToMaps(List<T> objList) {
        List<Map<String, ?>> list = new ArrayList<>();
        if (objList != null && objList.size() > 0) {
            Map<String, ?> map = null;
            T bean = null;
            for (int i = 0, size = objList.size(); i < size; i++) {
                bean = objList.get(i);
                map = beanToMap(bean);
                list.add(map);
            }
        }
        return list;
    }

    public static <T> List<T> mapsToObjects(List<Map<String, ?>> maps, Class<T> clazz)
            throws InstantiationException, IllegalAccessException {
        List<T> list = new ArrayList<>();
        if (maps != null && maps.size() > 0) {
            Map<String, ?> map = null;
            for (int i = 0, size = maps.size(); i < size; i++) {
                map = maps.get(i);
                T bean = mapToBean(map, clazz);
                list.add(bean);
            }
        }
        return list;
    }
}

1-2.调用

public class BeanMapToolTest {

    @Test
    public void testBeanToMap() {
        String[] hobbies = {"football", "sing"};
        UserVo user = new UserVo(1, "zhangsan", System.currentTimeMillis(), false, Arrays.asList(hobbies));
        Map<String, ?> map = BeanMapTool.beanToMap(user);
        System.out.println(map.get("name"));
    }

    @Test
    public void testMapToBean() {
        String[] hobbies = {"football", "sing"};
        Map<String, Object> map = new HashMap<>();
        map.put("id", 1);
        map.put("name", "zhangsan");
        map.put("birthday", System.currentTimeMillis());
        map.put("vip", false);
        map.put("hobbies", Arrays.asList(hobbies));

        try {
            UserVo userVo = BeanMapTool.mapToBean(map, UserVo.class);
            System.out.println(userVo.getHobbies());
        } catch (IllegalAccessException | InstantiationException e) {
            e.printStackTrace();
        }
    }
}

2.BeanUtils方式

导入pom依赖

<dependency>
    <groupId>commons-beanutils</groupId>
    <artifactId>commons-beanutils</artifactId>
    <version>1.9.3</version>
</dependency>

2-1.工具类BeanUtilsTool

package com.iworkh.test.restassured.utils;

import org.apache.commons.beanutils.BeanUtils;

import java.lang.reflect.InvocationTargetException;
import java.util.Map;

/**
 * Apache BeanUtils工具类
 *
 * @author: iworkh-沐雨云楼
 * @date: 2020-06-19
 */
public class BeanUtilsTool {

    public static <T> Map<String, String> beanToMap(T bean)
            throws IllegalAccessException, NoSuchMethodException, InvocationTargetException {
        return BeanUtils.describe(bean);
    }

    public static <T> T mapToBean(Map<String, Object> map, Class<T> bean)
            throws IllegalAccessException, InstantiationException, InvocationTargetException {
        T t = bean.newInstance();
        BeanUtils.populate(t, map);
        return t;
    }
}

2-2.调用

public class BeanUtilsToolTest {

    @Test
    public void testBeanToMap() {
        String[] hobbies = {"football", "sing"};
        UserVo user = new UserVo(1, "zhangsan", System.currentTimeMillis(), false, Arrays.asList(hobbies));
        try {
            Map<String, String> map = BeanUtilsTool.beanToMap(user);
            System.out.println(map.get("name"));
        } catch (IllegalAccessException | NoSuchMethodException | InvocationTargetException e) {
            e.printStackTrace();
        }
    }

    @Test
    public void testMapToBean() {
        String[] hobbies = {"football", "sing"};
        Map<String, Object> map = new HashMap<>();
        map.put("id", 1);
        map.put("name", "zhangsan");
        map.put("birthday", System.currentTimeMillis());
        map.put("vip", false);
        map.put("hobbies", Arrays.asList(hobbies));
        try {
            UserVo userVo = BeanUtilsTool.mapToBean(map, UserVo.class);
            System.out.println(userVo.getHobbies());

        } catch (IllegalAccessException | InstantiationException | InvocationTargetException e) {
            e.printStackTrace();
        }
    }
}

更多内容可以关注:iworkh博客

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值