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

com.es.plus.adapter.util.BeanUtils Maven / Gradle / Ivy

There is a newer version: 0.3.3
Show newest version
package com.es.plus.adapter.util;

import org.springframework.cglib.beans.BeanMap;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class BeanUtils {
    public static  Map beanToMap(T bean) {
        BeanMap beanMap = BeanMap.create(bean);
        Map map = new HashMap<>();

        beanMap.forEach((key, value) -> {
            map.put(String.valueOf(key), value);
        });
        return map;
    }

    public static  Map beanToMapIgnoreNull(T bean) {
        BeanMap beanMap = BeanMap.create(bean);
        Map map = new HashMap<>();

        beanMap.forEach((key, value) -> {
            if (value != null) {
                map.put(String.valueOf(key), value);
            }
        });
        return map;
    }

    public static  T mapToBean(Map map, Class clazz) {
        if (clazz.equals(Map.class)) {
            return (T) map;
        }
        T bean = null;
        try {
            bean = clazz.newInstance();
        } catch (InstantiationException | IllegalAccessException e) {
            throw new RuntimeException("instance error mapToBean");
        }
        BeanMap beanMap = BeanMap.create(bean);
        beanMap.putAll(map);
        return bean;
    }

    public static  List> beansToMaps(List beans) {
        List> list = new ArrayList<>();
        if (beans != null && beans.size() > 0) {
            Map map = null;
            T bean = null;
            for (int i = 0, size = beans.size(); i < size; i++) {
                bean = beans.get(i);
                map = beanToMap(bean);
                list.add(map);
            }
        }
        return list;
    }

    public static  List mapsToBeans(List> maps, Class clazz) {
        List list = new ArrayList<>();
        if (maps != null && maps.size() > 0) {
            Map map = null;
            for (int i = 0, size = maps.size(); i < size; i++) {
                map = maps.get(i);
                T bean = mapToBean(map, clazz);
                list.add(bean);
            }
        }
        return list;
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy