1. 程式人生 > >JAVA Map轉換為實體類和實體類轉換為MAP

JAVA Map轉換為實體類和實體類轉換為MAP

package com.ruiguang.tools;


import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


public class JavaBeanUtil {
private static Logger logger = LoggerFactory.getLogger(JavaBeanUtil.class);




    /**
     * 實體類轉map
     * @param obj
     * @return
     */
    public static Map<String, Object> convertBeanToMap(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);
                    if(null==value){
                        map.put(key,"");
                    }else{
                        map.put(key,value);
                    }
                }




            }
        } catch (Exception e) {
            logger.error("convertBean2Map Error {}" ,e);
        }
        return map;
    }




    /**
     * map 轉實體類
     * @param clazz
     * @param map
     * @param <T>
     * @return
     */
    public static <T> T convertMapToBean(Class<T> clazz, Map<String,Object> map) {
        T obj = null;
        try {
            BeanInfo beanInfo = Introspector.getBeanInfo(clazz);
            obj = clazz.newInstance(); // 建立 JavaBean 物件




            // 給 JavaBean 物件的屬性賦值
            PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
            for (int i = 0; i < propertyDescriptors.length; i++) {
                PropertyDescriptor descriptor = propertyDescriptors[i];
                String propertyName = descriptor.getName();
                if (map.containsKey(propertyName)) {
                    // 下面一句可以 try 起來,這樣當一個屬性賦值失敗的時候就不會影響其他屬性賦值。
                    Object value = map.get(propertyName);
                    if ("".equals(value)) {
                        value = null;
                    }
                    Object[] args = new Object[1];
                    args[0] = value;
                    descriptor.getWriteMethod().invoke(obj, args);




                }
            }
        } catch (IllegalAccessException e) {
            logger.error("convertMapToBean 例項化JavaBean失敗 Error{}" ,e);
        } catch (IntrospectionException e) {
            logger.error("convertMapToBean 分析類屬性失敗 Error{}" ,e);
        } catch (IllegalArgumentException e) {
            logger.error("convertMapToBean 對映錯誤 Error{}" ,e);
        } catch (InstantiationException e) {
            logger.error("convertMapToBean 例項化 JavaBean 失敗 Error{}" ,e);
        }catch (InvocationTargetException e){
            logger.error("convertMapToBean欄位對映失敗 Error{}" ,e);
        }catch (Exception e){
            logger.error("convertMapToBean Error{}" ,e);
        }
        return (T) obj;
    }
    //將map通過反射轉化為實體
    public static   Object MapToModel(Map<String,Object> map,Object o) throws Exception{
        if (!map.isEmpty()) {
            for (String k : map.keySet()) {
                Object v =null;
                if (!k.isEmpty()) {
                    v = map.get(k);
                }
                Field[] fields = null;
                fields = o.getClass().getDeclaredFields();
                String clzName = o.getClass().getSimpleName();
                for (Field field : fields) {
                    int mod = field.getModifiers();


                    if (field.getName().toUpperCase().equals(k.toUpperCase())) {
                        field.setAccessible(true);


                        //region--進行型別判斷
                          String type=field.getType().toString();
                          if (type.endsWith("String")){
                              if (v!=null){
                                  v=v.toString();
                              }else {
                                  v="";
                              }
                          }
                        if (type.endsWith("Date")){
                            v=new Date(v.toString());
                        }
                        if (type.endsWith("Boolean")){


                           v=Boolean.getBoolean(v.toString());
                        }
                        if (type.endsWith("int")){


                            v=new Integer(v.toString());
                        }
                        if (type.endsWith("Long")){


                            v=new Long(v.toString());
                        }






                        //endregion
                        field.set(o, v);


                    }


                }


            }
        }
        return o;
    }
    /**
     * 實體物件轉成Map
     * @param obj 實體物件
     * @return
     */
    public static Map<String, Object> object2Map(Object obj) {
        Map<String, Object> map = new HashMap<>();
        if (obj == null) {
            return map;
        }
        Class clazz = obj.getClass();
        Field[] fields = clazz.getDeclaredFields();
        try {
            for (Field field : fields) {
                field.setAccessible(true);
                map.put(field.getName(), field.get(obj));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return map;
    }
    /**
     * Map轉成實體物件
     * @param map map實體物件包含屬性
     * @param clazz 實體物件型別
     * @return
     */
    public static Object map2Object(Map<String, Object> map, Class<?> clazz) {
        if (map == null) {
            return null;
        }
        Object obj = null;
        try {
            obj = clazz.newInstance();




            Field[] fields = obj.getClass().getDeclaredFields();
            for (Field field : fields) {
                int mod = field.getModifiers();
                if (Modifier.isStatic(mod) || Modifier.isFinal(mod)) {
                    continue;
                }
                field.setAccessible(true);
                field.set(obj, map.get(field.getName()));
            }
        } catch (Exception e) {
            e.printStackTrace();
        } 
        return obj;
    }
    
    public static void main(String[] args) {
    // TODO Auto-generated method stub
    /*Student s = new Student();
          s.setUserName("ZHH");
          s.setAge("24");
          System.out.println(object2Map(s));




          Map<String, Object> map = new HashMap<>();
          map.put("userName", "zhh");
          map.put("age", "24");
          System.out.println(map2Object(map, Student.class));*/
    }
    


}