All Downloads are FREE. Search and download functionalities are using the official Maven repository.

cn.foxtech.common.utils.bean.BeanMapUtils Maven / Gradle / Ivy

/* ----------------------------------------------------------------------------
 * Copyright (c) Guangzhou Fox-Tech Co., Ltd. 2020-2024. All rights reserved.
 * --------------------------------------------------------------------------- */

package cn.foxtech.common.utils.bean;

import org.springframework.cglib.beans.BeanMap;

import java.util.*;

/**
 * BeanMap反射工具
 */
public class BeanMapUtils {
    /**
     * map转java对象
     *
     * @param map       Map对象
     * @param beanClass 待构造的对象类型
     * @return 对象
     * @throws Exception 转换异常
     */
    public static Object mapToObject(Map map, Class beanClass) throws Exception {
        Object object = beanClass.newInstance();
        BeanMap beanMap = BeanMap.create(object);
        beanMap.putAll(map);
        return object;
    }

    /**
     * 将对象转换为Map
     *
     * @param obj 对象
     * @return Map
     */
    public static Map objectToMap(Object obj) {
        Map map = new HashMap<>();
        if (obj != null) {
            BeanMap beanMap = BeanMap.create(obj);
            for (Object key : beanMap.keySet()) {
                map.put(key + "", beanMap.get(key));
            }
        }
        return map;
    }

    /**
     * 生成的Map后,剔除指定的key
     *
     * @param objectList 对象
     * @param filterKeys 要剔除的Key
     * @param         类型名
     * @return map
     */
    public static  List> objectToMap(Collection objectList, List filterKeys) {
        List> result = new ArrayList<>();
        for (T entity : objectList) {
            Map map = BeanMapUtils.objectToMap(entity);

            for (String filter : filterKeys) {
                map.remove(filter);
            }

            result.add(map);
        }

        return result;
    }

    public static  void filterKeys(List> objectList, List filterKeys) {
        List> result = new ArrayList<>();
        for (Map map : objectList) {
            for (String filter : filterKeys) {
                map.remove(filter);
            }

            result.add(map);
        }
    }

    public static  List> objectToMap(Collection objectList) {
        List> result = new ArrayList<>();
        for (T entity : objectList) {
            Map map = BeanMapUtils.objectToMap(entity);

            result.add(map);
        }

        return result;
    }

    /**
     * 生成的Map后,剔除指定的key
     *
     * @param object     对象
     * @param filterKeys 要剔除的Key
     * @param 
     * @return map
     */
    public static  Map objectToMap(T object, List filterKeys) {
        Map map = BeanMapUtils.objectToMap(object);

        for (String filter : filterKeys) {
            map.remove(filter);
        }

        return map;
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy