Java 对象复制工具类

Java 对象复制工具类

java 复制代码
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ Author:aqrlmy
 */
@SuppressWarnings(value = "unused")
@Slf4j
public class BeanUtils {


    /**
     * 将List中的对象拷贝到目标对象的List中(标准Bean)
     *
     * @param sourceList 源List<T>
     * @param targetCls  目标对象类型
     * @param <T>        源类型
     * @param <R>        目标类型
     * @return 目标类型List数组
     */
    public static <T, R> List<R> beanCopyPropertiesForList(List<T> sourceList, Class<R> targetCls) {
        if (sourceList == null) {
            return null;
        }
        Assert.notNull(targetCls, "target class can not null");
        List<R> targetList = new ArrayList<>();
        if (!sourceList.isEmpty()) {
            for (T source : sourceList) {
                targetList.add(beanCopyProperties(source, targetCls));
            }
        }
        return targetList;
    }


    /**
     * 属性值拷贝(标准Bean)
     *
     * @param source    源对象
     * @param targetCls 目标对象类
     * @Return 拷贝目标类的实体
     */
    public static <R> R beanCopyProperties(Object source, Class<R> targetCls) {
        try {
            if (source == null) {
                return null;
            }
            Assert.notNull(targetCls, "target class can not null");
            R target = targetCls.getDeclaredConstructor().newInstance();
            org.springframework.beans.BeanUtils.copyProperties(source, target);
            return target;
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return null;
        }
    }

    public static <R> R copyProperties(Object source, Class<R> targetCls) {
        return beanCopyProperties(source, targetCls);
    }

    /**
     * 属性值拷贝(标准Bean)
     *
     * @param source 源对象
     * @param target 目标对象
     * @Return 拷贝目标类的实体
     */
    public static <R> R copyProperties(Object source, R target) {
        try {
            if (source == null) {
                return null;
            }
            Assert.notNull(target, "target class can not null");
            org.springframework.beans.BeanUtils.copyProperties(source, target);
            return target;
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return null;
        }
    }

    /**
     * 属性值拷贝(标准Bean)
     *
     * @param source    源对象
     * @param targetCls 目标对象类
     * @return 拷贝目标类的实体
     */
    public static <R> R beanCopyProperties(Object source, Class<R> targetCls,
                                           String ignoreProperties) {
        try {
            if (source == null) {
                return null;
            }
            Assert.notNull(targetCls, "target class can not null");
            R target = targetCls.getDeclaredConstructor().newInstance();
            if (StringUtils.isEmpty(ignoreProperties)) {
                org.springframework.beans.BeanUtils.copyProperties(source, target);
            } else {
                org.springframework.beans.BeanUtils.copyProperties(source, target, ignoreProperties.split(","));
            }
            return target;
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return null;
        }
    }

    /**
     * bean 对象拷贝
     */
    public static <R> R beanCopyProperties(Object source, Class<R> target, R defVal) {
        return beanCopyProperties(source, target, defVal, null);
    }

    /**
     * bean 对象拷贝
     *
     * @param source           原始对象
     * @param target           目标对象类
     * @param defVal           默认值生成器: 原始对象为null, 返回该值
     * @param ignoreProperties 拷贝时忽略字段名, 忽略多个字段使用逗号分割
     * @param <R>              目标类
     * @return 生成实体
     */
    public static <R> R beanCopyProperties(Object source, Class<R> target, R defVal,
                                           String ignoreProperties) {
        if (source == null) {
            return defVal;
        }
        return beanCopyProperties(source, target, ignoreProperties);
    }

    /**
     * 属性值拷贝(标准Bean)
     *
     * @param source 源对象
     * @param target 目标对象
     * @return 拷贝目标类的实体
     */
    public static void beanCopyProperties(Object source, Object target, String ignoreProperties) {
        try {
            Assert.notNull(target, "target can not null");
            if (source == null) {
                return;
            }
            if (StringUtils.isEmpty(ignoreProperties)) {
                org.springframework.beans.BeanUtils.copyProperties(source, target);
            } else {
                org.springframework.beans.BeanUtils.copyProperties(source, target, ignoreProperties.split(","));
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }

    /**
     * Get value or default value if it is null.
     *
     * @param value        原值
     * @param defaultValue 默认值
     * @param <T>          类型
     * @return 结果
     */
    public static <T> T valueOrDefault(T value, T defaultValue) {
        return value == null ? defaultValue : value;
    }

    /**
     * Return the named getter method on the bean or null if not found.
     *
     * @return the named getter method
     */
    private static Method getMethod(Object bean, String propertyName) {
        StringBuilder sb = new StringBuilder("get")
                .append(Character.toUpperCase(propertyName.charAt(0)));
        if (propertyName.length() > 1) {
            sb.append(propertyName.substring(1));
        }
        String getterName = sb.toString();
        for (Method m : bean.getClass().getMethods()) {
            if (getterName.equals(m.getName()) && m.getParameterTypes().length == 0) {
                return m;
            }
        }
        return null;
    }

    /**
     * Return the named field on the bean or null if not found.
     *
     * @return the named field
     */
    private static Field getField(Object bean, String propertyName) {
        for (Field f : bean.getClass().getDeclaredFields()) {
            if (propertyName.equals(f.getName())) {
                return f;
            }
        }
        return null;
    }

    private static void validateArgs(Object bean, String propertyName) {
        if (bean == null) {
            throw new IllegalArgumentException("bean is null");
        }
        if (propertyName == null) {
            throw new IllegalArgumentException("propertyName is null");
        }
        if (propertyName.trim().length() == 0) {
            throw new IllegalArgumentException("propertyName is empty");
        }
    }

    /**
     * Retrieve a named bean property value.
     *
     * @param bean bean
     * @return the property value
     */
    public static Object getBeanProperty(Object bean, String propertyName) {
        validateArgs(bean, propertyName);

        // try getters first
        Method getter = getMethod(bean, propertyName);
        if (getter != null) {
            try {
                return getter.invoke(bean);
            } catch (Exception ignored) {
            }
        }

        Field field = getField(bean, propertyName);
        if (field != null) {
            try {
                field.setAccessible(true);
                return field.get(bean);
            } catch (Exception ignored) {
            }
        }

        return null;
    }

    /**
     * Retrieve a Long bean property value.
     *
     * @param bean bean
     * @return long value
     */
    public static long getLongBeanProperty(final Object bean, final String propertyName)
            throws NoSuchFieldException {
        validateArgs(bean, propertyName);
        Object o = getBeanProperty(bean, propertyName);
        if (o == null) {
            throw new NoSuchFieldException(propertyName);
        } else if (!(o instanceof Number)) {
            throw new IllegalArgumentException(propertyName + " not an Number");
        }
        return ((Number) o).longValue();
    }

    public static <R> R mapToClass(Map<String, ?> params, Class<R> targetCls) {
        Assert.notEmpty(params, "params can not empty");
        try {
            return JSON.parseObject(JSON.toJSONString(params), targetCls);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return null;
        }
    }

    public static Map<String, Object> beanToMap(Object obj) {
        Assert.notNull(obj, "params can not empty");
        Map<String, Object> map = new HashMap<>();
        Class<?> clazz = obj.getClass();
        try {
            for (Field field : clazz.getDeclaredFields()) {
                field.setAccessible(true);
                String fieldName = field.getName();
                Object value = field.get(obj);
                map.put(fieldName, value);
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return null;
        }
        return map;
    }


}
相关推荐
basketball6164 小时前
C++ NULL 和 nullptr 区别 以及 nullptr 的核心实现
java·开发语言·c++
JAVA面经实录9175 小时前
MyBatis面试题库
java·mybatis
小江的记录本5 小时前
【JVM虚拟机】垃圾回收GC:垃圾回收算法:标记-清除、标记-复制、标记-整理、分代收集(附《思维导图》+《面试高频考点清单》)
java·jvm·后端·python·算法·安全·面试
小江的记录本6 小时前
【JVM虚拟机】垃圾回收GC:垃圾收集器:G1:Region分区、Mixed GC、回收流程、适用场景(高频)(附《思维导图》+《面试高频考点清单》)
java·jvm·后端·python·spring·spring cloud·面试
摇滚侠6 小时前
Java 零基础全套教程,反射机制,笔记 187-188
java·开发语言·笔记
超梦dasgg7 小时前
Java 生产环境第三方对接安全保障方案
java·开发语言·安全
日月云棠7 小时前
9 Double 与 Float —— IEEE 754 浮点数在 Java 中的实现
java·后端
Refrain_zc7 小时前
Android 二维码登录轮询机制:从扫码到登录的完整客户端实现
java
z落落7 小时前
C#参数区别
java·算法·c#
日月云棠7 小时前
5 StringBuffer —— 线程安全的可变字符串
java·后端