1. 程式人生 > 實用技巧 >Java實體類Bean與Map互相轉化(兩種方式)

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 + "]";
    }

}