package com.xisc.pm.infra.util;

import lombok.extern.slf4j.Slf4j;

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

@Slf4j
public class ObjectToMapUtil {

    /**
     * 对象转Map
     * @param object
     * @return
     */
    public static Map<String, Object> beanToMap(Object object)  {
        Map<String, Object> map = new HashMap<String, Object>();
        Field[] fields = object.getClass().getDeclaredFields();
        for (Field field : fields) {
            if(field.getName().contains("FIELD_")) {
                continue;
            }
            field.setAccessible(true);
            try {
                map.put(field.getName(), field.get(object));
            } catch (IllegalAccessException e) {
                log.error(e.getMessage(), e);
            }
        }
        return map;
    }

    /**
     * map转对象
     * @param map
     * @param beanClass
     * @param <T>
     * @return
     */
    @SuppressWarnings("rawtypes")
    public static <T> T mapToBean(Map map, Class<T> beanClass){
        T object = null;
        try {
            object = beanClass.newInstance();
            Field[] fields = object.getClass().getDeclaredFields();
            for (Field field : fields) {
                int mod = field.getModifiers();
                if (Modifier.isStatic(mod) || Modifier.isFinal(mod)) {
                    continue;
                }
                field.setAccessible(true);
                if (map.containsKey(field.getName())) {
                    field.set(object, map.get(field.getName()));
                }
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return object;
    }
}