package com.base.orbit.lucene.utils;

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

public class MapUtil {
    /*对象转map*/
    public static Map<String,Object> objectToMap(Object object) {
        Map<String,Object> dataMap=new HashMap<>();
        Class<?> clazz=object.getClass();
        for (Field field:clazz.getDeclaredFields()){
            try{
                field.setAccessible(true);
                dataMap.put(field.getName(),field.get(object));

            }catch (IllegalAccessException e){
                e.printStackTrace();
            }
        }
        return dataMap;
    }

    /*map转object*/
    public static Object mapToObject(Map<String,Object> map,Class<?> clz) {
        Object obj= null;
        try {
            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()));
            }
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }

        return obj;
    }
}
