关于Javabean和map之间的互相转换

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

    /**
     * 把一个bean中的属性转化到map中
     *
     * @param bean bean对象
     */
    public static Map bean2Map(Object bean) {
        if (bean == null) {
            return null;
        }
        Map fieldMap = new HashMap<>();
        BeanInfo beanInfo = null;
        try {
            beanInfo = Introspector.getBeanInfo(bean.getClass(), Object.class);
            PropertyDescriptor[] pds = beanInfo.getPropertyDescriptors();
            for (PropertyDescriptor pd : pds) {
                String key = pd.getName();
                Method getter = pd.getReadMethod();
                Object value = getter.invoke(bean);
                fieldMap.put(key, value);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return fieldMap;
    }

    /**
     * map转Javabean
     *
     * @param map
     * @param beanClass
     * @return
     * @throws Exception
     */
    public static Object map2Object(Map map, Class beanClass) {
        if (map == null)
            return null;
        Object obj = null;
        try {
            obj = beanClass.newInstance();
            BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
            PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
            for (PropertyDescriptor property : propertyDescriptors) {
                Method setter = property.getWriteMethod();
                if (setter != null) {
                    setter.invoke(obj, map.get(property.getName()));
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return obj;
    }

 

你可能感兴趣的:(Android,Java)