Java实体类Bean与Map互相转化(两种方式)

前言:

实体类和map相互转换,实体类需要有无参构造,不然会出现异常。

 

一:BeanUtils类来实现

pom:

<dependency>
     <groupId>commons-beanutils</groupId>
     <artifactId>commons-beanutils</artifactId>
     <version>1.8.0</version>
     <scope>compile</scope>
</dependency>

<dependency>
     <groupId>commons-logging</groupId>
     <artifactId>commons-logging</artifactId>
     <version>1.2</version>
</dependency>

 

 代码:

package com.x;

import java.util.HashMap;
import java.util.Map;

import org.apache.commons.beanutils.BeanUtils;

public class BeanTest {
    public static Map<String, Object> beanToMap(Object bean) {
        if (null == bean)
            return null;
        try {
            Map<String, Object> map = BeanUtils.describe(bean);
            // 移除key=class
            map.remove("class");

            System.out.println("JavaBean-->Map转换前:" + bean.toString());
            System.out.println("JavaBean-->Map转换后:" + map);
            return map;
        } catch (Exception e) {
            System.out.println("JavaBean-->Map转换失败:" + e.getMessage());
            e.printStackTrace();
            return null;
        }
    }

    public static <T> T mapToBean(Class<?> clazz, Map map) {
        try {
            T newBeanInstance = (T) clazz.newInstance();
            BeanUtils.populate(newBeanInstance, map);
            System.out.println("Map-->JavaBean转换前:" + map);
            System.out.println("Map-->JavaBean转换后:" + newBeanInstance.toString());
            return newBeanInstance;
        } catch (Exception e) {
            System.out.println("Map-->JavaBean转换失败:" + e.getMessage());
            e.printStackTrace();
            return null;
        }
    }

    public static void main(String[] args) {
        Map<String, Object> hashMap = new HashMap<>();
        hashMap.put("name", "谢辉");
        hashMap.put("age", 18);
        // map转实体类
        Xieh people = mapToBean(Xieh.class, hashMap);

        // 实体类转map
        Map map = beanToMap(people);

        // 打印执行结果
        System.out.println(people.toString());
        System.out.println(map);
    }
}

 

 

二:jdk自带方法

代码:

package com.x2;

import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

public class BeanTest {

    public static Map<String, Object> bean2Map(Object obj) {
        if (obj == null) {
            return null;
        }
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
            PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
            for (PropertyDescriptor property : propertyDescriptors) {
                String key = property.getName();
                // 过滤class属性
                if (!key.equals("class")) {
                    // 得到property对应的getter方法
                    Method getter = property.getReadMethod();
                    Object value = getter.invoke(obj);
                    map.put(key, value);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return map;
    }

    public static Object mapToBean(Class type, Map map) {
        Object obj = null;
        try {
            BeanInfo beanInfo = Introspector.getBeanInfo(type);
            obj = type.newInstance();
            PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
            for (PropertyDescriptor descriptor : propertyDescriptors) {
                String propertyName = descriptor.getName();
                if (map.containsKey(propertyName)) {
                    Object value = map.get(propertyName);
                    descriptor.getWriteMethod().invoke(obj, value);
                }
            }
        } catch (Exception e) {
            System.out.println("map转实体类出现异常");
        }
        return obj;
    }

    public static void main(String[] args) {
        Xieh xieh = new Xieh();
        xieh.setName("谢辉");
        xieh.setAge(23);

        Map<String, Object> map = bean2Map(xieh);
        System.out.println(map.toString());
        Xieh object = (Xieh) mapToBean(Xieh.class, map);
        System.out.println(object.toString());
    }
}

 

 

测试实体类

package com.x2;

import java.io.Serializable;

public class Xieh implements Serializable {
    private String name;
    private int age;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

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

    @Override
    public String toString() {
        return "Xieh [name=" + name + ", age=" + age + "]";
    }

}

 

posted @ 2020-12-10 19:31  图图小淘气_real  阅读(7120)  评论(0编辑  收藏  举报