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

org.yes.tools.utils.BeanCopyUtils Maven / Gradle / Ivy

There is a newer version: 2.0.4
Show newest version
package org.yes.tools.utils;

import cn.hutool.core.bean.BeanUtil;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Field;
import java.util.*;

/**
 * @author Co.
 * @date 2022年 06月14日 11:47:42
 */
@Slf4j
public class BeanCopyUtils {
    /**
     * 复制某个对象为目标对象类型的对象 当source与target对象属性名相同, 但数据类型不一致时,source的属性值不会复制到target对象
     *
     * @param       目标对象类型参数
     * @param source   源对象
     * @param destType 目标对象类型
     * @return
     */
    public static  T copyAs(Object source, Class destType) {
        if (Objects.isNull(source) || Objects.isNull(destType)) {
            return null;
        }
        try {
            T dest = destType.newInstance();
            copy(source, dest);
            return dest;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 复制源对象集合到目标对象列表
     *
     * @param 
     * @param source
     * @param destType
     * @return
     */
    public static  List copyListAs(Collection source, Class destType) {
        if (Objects.isNull(source) || Objects.isNull(destType)) {
            return Collections.emptyList();
        }

        List result = new ArrayList<>();
        if (source.isEmpty()) {
            return result;
        }

        try {
            Iterator iterator = source.iterator();
            Class sourceClass = iterator.next().getClass();
            for (Object object : source) {
                K dest = destType.newInstance();
                copy(object, dest);
                result.add(dest);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return result;
    }

    /**
     * 复制属性:从源对象复制和目标对象相同的属性
     *
     * @param source 源对象
     * @param target 目标对象
     */
    private static void copy(Object source, Object target) {
        if (Objects.isNull(source) || Objects.isNull(target)) {
            return;
        }
        BeanUtil.copyProperties(source, target, true);
    }

    /**
     * 设置Field值
     *
     * @param bean      要设置对象
     * @param fieldName 字段名
     * @param value     值
     */
    private static void setFieldValue(Object bean, String fieldName, Object value) {
        try {
            Field field = findField(bean.getClass(), fieldName);
            field.setAccessible(true);
            field.set(bean, value);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 取得指定名称的Field, 子类找不到, 去父类里找
     *
     * @param clz       类
     * @param fieldName 指定名称
     * @return 找不到返回null
     */
    private static Field findField(Class clz, String fieldName) {
        Field f = null;
        try {
            f = clz.getDeclaredField(fieldName);
        } catch (NoSuchFieldException e) {
            if (clz.getSuperclass() != null) {
                f = findField(clz.getSuperclass(), fieldName);
            }
            if (log.isTraceEnabled()) {
                log.trace(e.getMessage());
            }
        }
        return f;
    }

    // ------------------------------------------------------------------------------------------------------------------------

    private static String[] getNullPropertyNames(Object source) {
        final org.springframework.beans.BeanWrapper beanWrapper = new org.springframework.beans.BeanWrapperImpl(source);
        java.beans.PropertyDescriptor[] pds = beanWrapper.getPropertyDescriptors();

        Set emptyNames = new HashSet();
        for (java.beans.PropertyDescriptor pd : pds) {
            Object propertyValue = beanWrapper.getPropertyValue(pd.getName());
            if (propertyValue == null) {
                emptyNames.add(pd.getName());
            } else {
                if (Iterable.class.isAssignableFrom(propertyValue.getClass())) {
                    Iterable iterable = (Iterable) propertyValue;
                    Iterator iterator = iterable.iterator();
                    if (!iterator.hasNext()) emptyNames.add(pd.getName());
                }
                if (Map.class.isAssignableFrom(propertyValue.getClass())) {
                    Map map = (Map) propertyValue;
                    if (map.isEmpty()) emptyNames.add(pd.getName());
                }
            }
        }
        String[] result = new String[emptyNames.size()];
        return emptyNames.toArray(result);
    }

    public static void copyProperties(Object source, Object target) {
        if (Objects.isNull(source) || Objects.isNull(target)) {
            return;
        }
        org.springframework.beans.BeanUtils.copyProperties(source, target, getNullPropertyNames(source));
    }

    public static void copyProperties(Object source, Object target, String... ignoreProperties) {
        if (Objects.isNull(source) || Objects.isNull(target)) {
            return;
        }
        org.springframework.beans.BeanUtils.copyProperties(source, target, ignoreProperties);
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy