package com.inkasso.adapter.util;

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

public class Obj2MapUtils {

    /**
     * 将Object类型的数据转化成Map<String,Object>
     * @param obj
     * @return
     * @throws Exception
     */
    public static Map<String,Object> obj2Map(Object obj) throws Exception{
        Map<String,Object> map=new LinkedHashMap<>();
        Field[] fields = obj.getClass().getDeclaredFields();
        for(Field field:fields){
            field.setAccessible(true);
            map.put(field.getName(), field.get(obj));
        }
        return map;
    }

    /**
     * 将Map<String,Object>类型的数据转化成Object
     * @return
     * @throws Exception
     */
    public Object map2Obj(Map<String,Object> map,Class<?> clz) throws Exception{
        Object obj = clz.newInstance();
        Field[] declaredFields = obj.getClass().getDeclaredFields();
        for(Field field:declaredFields){
            int mod = field.getModifiers();
            if(Modifier.isStatic(mod) || Modifier.isFinal(mod)){
                continue;
            }
            field.setAccessible(true);
            field.set(obj, map.get(field.getName()));
        }
        return obj;
    }
}
