欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

map转bean,bean转map

程序员文章站 2024-02-15 19:30:34
...

有一个UserInfo类,如下:

public class UserInfo {
    private int id;
    private String userName;
    public int age;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "id=" + id + ",username=" + userName + ",age=" + age;
    }
}

直接使用BeanMap来做转换,如下:

import org.springframework.cglib.beans.BeanMap;

import java.beans.IntrospectionException;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Map;

public class CommonUtils {
    /**
     * map转bean
     *
     * @param map
     * @param bean
     * @param <T>
     * @return
     */
    public static <T> T map2Bean(Map<String, Object> map, T bean) {
        BeanMap beanMap = BeanMap.create(bean);
        beanMap.putAll(map);
        return bean;
    }

    /**
     * bean转map
     *
     * @param bean
     * @param <T>
     * @return
     */
    public static <T> Map<String, Object> bean2Map(T bean) {
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            if (bean != null) {
                BeanMap beanMap = BeanMap.create(bean);
                map.putAll(beanMap);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return map;
    }

    public static void main(String[] args) throws IllegalAccessException, IntrospectionException, InvocationTargetException {
        Map<String, Object> map = new HashMap<>();
        map.put("id", 1);
        map.put("userName", "jiejie");
        map.put("age", 36);
        UserInfo userInfo = new UserInfo();
        UserInfo o = CommonUtils.map2Bean(map, userInfo);
        System.out.println("map2Bean:" + o);
        System.out.println("bean2Map:" + CommonUtils.bean2Map(o));
    }
}

测试结果:
map转bean,bean转map