package com.benyun.common.utils;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.HashMap;
import java.util.Map;

public class MapUtils {
    //Map转对象
    public static Object mapToObject(Map<String, Object> map, Class<?> beanClass) throws Exception {
        if (map == null)
            return null;

        Object obj = beanClass.newInstance();

        Field[] fields = obj.getClass().getDeclaredFields();
        for (Field field : fields) {
            int mod = field.getModifiers();
            if(Modifier.isStatic(mod) || Modifier.isFinal(mod)){
                continue;
            }

            if(map.get(field.getName()) == null){
                continue;
            }

            field.setAccessible(true);
            if(field.getType().getName().equals("java.lang.Long")){
                field.set(obj, Long.valueOf(map.get(field.getName()) + ""));
            }else if(field.getType().getName().equals("java.lang.Double")){
                field.set(obj, Double.valueOf(map.get(field.getName()) + ""));
            }else if(field.getType().getName().equals("java.lang.Integer")){
                field.set(obj, Integer.valueOf(map.get(field.getName()) + ""));
            }else{
                field.set(obj, map.get(field.getName()));
            }
        }

        return obj;
    }


    //对象转Map
    public static Map<String, Object> objectToMap(Object obj) throws Exception {
        if(obj == null){
            return null;
        }

        Map<String, Object> map = new HashMap<String, Object>();

        Field[] declaredFields = obj.getClass().getDeclaredFields();
        for (Field field : declaredFields) {
            field.setAccessible(true);
            map.put(field.getName(), field.get(obj));
        }

        return map;
    }
}
