package com.ruoyi.common.utils;

import org.apache.commons.beanutils.BeanUtils;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;

import java.util.Map;

public class MapToObjectUtils {

    public static <T> T populate(Map<String, ?> map, Class<T> clazz) throws Exception {
        T obj = clazz.getDeclaredConstructor().newInstance();
        BeanUtils.populate(obj, map); // 自动匹配Map键和对象属性名
        return obj;
    }

    public static <T> T mapToBean(Map<String, ?> map, Class<T> clazz) throws Exception {
        T obj = clazz.getDeclaredConstructor().newInstance();
        BeanWrapper wrapper = new BeanWrapperImpl(obj);
        for (Map.Entry<String, ?> entry : map.entrySet()) {
            wrapper.setPropertyValue(entry.getKey(), entry.getValue());
        }
        return obj;
    }
}
