Bean增强类工具类(数据转换 1.0 version)

示例:
1、数据转换
List<ProAssignmentOrderEquip> equips = list(wrapper);
List<ProAssignmentOrderEquipResultVO> list = BeanPlusUtil.toBeanList(equips, ProAssignmentOrderEquipResultVO.class);
2、数据复制(可以忽略字段进行复制)
ManageSummaryEmployeeWages oldSource = new ManageSummaryEmployeeWages();
ManageSummaryEmployeeWages target = new ManageSummaryEmployeeWages();
BeanPlusUtil.copyProperties(oldSource, target, "id", "companyDate");
import cn.afterturn.easypoi.excel.annotation.Excel;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * Bean增强类工具类
 *
 * <p>
 * 把一个拥有对属性进行set和get方法的类,我们就可以称之为JavaBean。
 * </p>
 *
 * @author zuihou
 * @since 3.1.2
 */
public class BeanPlusUtil extends BeanUtil {

    /**
     * 转换 list
     *
     * @param sourceList       源集合
     * @param destinationClass 目标类型
     * @return 目标集合
     */
    public static <T, E> List<T> toBeanList(Collection<E> sourceList, Class<T> destinationClass) {
        if (sourceList == null || sourceList.isEmpty() || destinationClass == null) {
            return Collections.emptyList();
        }
        return sourceList.parallelStream()
                .filter(Objects::nonNull)
                .map(source -> toBean(source, destinationClass))
                .collect(Collectors.toList());
    }

    /**
     * 转化Page 对象
     *
     * @param page             分页对象
     * @param destinationClass 目标类型
     * @return 目录分页对象
     */
    public static <T, E> IPage<T> toBeanPage(IPage<E> page, Class<T> destinationClass) {
        if (page == null || destinationClass == null) {
            return null;
        }
        IPage<T> newPage = new Page<>(page.getCurrent(), page.getSize());
        newPage.setPages(page.getPages());
        newPage.setTotal(page.getTotal());

        List<E> list = page.getRecords();
        if (CollUtil.isEmpty(list)) {
            return newPage;
        }

        List<T> destinationList = toBeanList(list, destinationClass);

        newPage.setRecords(destinationList);
        return newPage;
    }


    //确保你的clazz有无参构造函数
    public static <T> List<T> excelMapToBean(List<Map<String, Object>> maps, Class<T> clazz) throws NoSuchMethodException{
        Field[] declaredFields = clazz.getDeclaredFields();


        Map<String, String> excelName2FieldName = new HashMap<>(declaredFields.length);
        for (Field field : declaredFields) {
            field.setAccessible(true);

            if (!field.isAnnotationPresent(Excel.class)) {
                continue;
            }

            Excel excel = field.getAnnotation(Excel.class);

            if (excel == null) {
                continue;
            }


            excelName2FieldName.put(excel.name(), field.getName());
        }

        if (excelName2FieldName.isEmpty()) {
            return Collections.emptyList();
        }


        List<Map<String, Object>> dataMap = maps.stream().map(map -> {

            Map<String, Object> one = new HashMap<>(map.size());

            for (Map.Entry<String, Object> entry : map.entrySet()) {
                if (!excelName2FieldName.containsKey(entry.getKey())) {
                    continue;
                }

                one.put(excelName2FieldName.get(entry.getKey()), entry.getValue());

            }

            return one;
        }).collect(Collectors.toList());


        List<T> result = new ArrayList<>();
        for (Map<String, Object> one : dataMap) {
            try {
                T obj = clazz.getDeclaredConstructor().newInstance();

                T t = BeanPlusUtil.fillBeanWithMap(one, obj, true, false);

                result.add(t);
            }catch (InstantiationException | IllegalAccessException | InvocationTargetException e) {
                throw new RuntimeException(e);
            }
        }

        return result;



    }
    public static <T> T  excelMapToBean(Map<String, Object> maps, Class<T> clazz) throws NoSuchMethodException{
        Field[] declaredFields = clazz.getDeclaredFields();


        Map<String, String> excelName2FieldName = new HashMap<>(declaredFields.length);
        for (Field field : declaredFields) {
            field.setAccessible(true);

            if (!field.isAnnotationPresent(Excel.class)) {
                continue;
            }

            Excel excel = field.getAnnotation(Excel.class);

            if (excel == null) {
                continue;
            }

            excelName2FieldName.put(excel.name(), field.getName());
        }

        if (excelName2FieldName.isEmpty()) {
            try {
                return clazz.getDeclaredConstructor().newInstance();
            }catch (InstantiationException | IllegalAccessException | InvocationTargetException e) {
                throw new RuntimeException(e);
            }
        }


        Map<String, Object> dataMap = new HashMap<>(maps.size());
        for (Map.Entry<String, Object> entry : maps.entrySet()) {
            if (!excelName2FieldName.containsKey(entry.getKey())) {
                continue;
            }
            dataMap.put(excelName2FieldName.get(entry.getKey()), entry.getValue());
        }

        try {
            T obj = clazz.getDeclaredConstructor().newInstance();

            return BeanPlusUtil.fillBeanWithMap(dataMap, obj, true, false);

        }catch (InstantiationException | IllegalAccessException | InvocationTargetException e) {
            throw new RuntimeException(e);
        }
    }

    public static <T> T trim(T bean){
        if (bean == null) {
            return null;
        }

        BeanWrapper beanWrapper = new BeanWrapperImpl(bean);
        java.beans.PropertyDescriptor[] descriptors = beanWrapper.getPropertyDescriptors();

        for (java.beans.PropertyDescriptor descriptor : descriptors) {
            if (descriptor.getPropertyType() == String.class &&
                    beanWrapper.isWritableProperty(descriptor.getName())) {

                Object value = beanWrapper.getPropertyValue(descriptor.getName());
                if (value instanceof String) {
                    String trimmed = ((String) value).trim();
                    beanWrapper.setPropertyValue(descriptor.getName(), trimmed);
                }
            }
        }

        return bean;
    }
}

 

posted @ 2026-05-27 15:36  岁月记忆  阅读(6)  评论(0)    收藏  举报