Copy工具类

package com;

import cn.hutool.core.convert.Convert;
import lombok.SneakyThrows;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;

import java.beans.PropertyDescriptor;
import java.util.*;

public class QQCopy {

    //region 对象
    @SneakyThrows
    public static <T> T copy(Object source, Class<T> target) {
        if (source == null || target == null)
            return null;
        T t = target.newInstance();
        BeanUtils.copyProperties(source, t);
        return t;
    }

    //复制对象属性,一个改变另一个也改变
    @SneakyThrows
    public static <T> T copyChange(Object source, Class<T> target) {
        return Convert.convert(target, source);
    }

    //复制对象属性到另一个对象,修改不会改变
    public static void copyProperties(Object source, Object target) {
        BeanUtils.copyProperties(source, target);
    }

    //复制对象属性到另一个对象,只复制属性有值的,修改不会改变
    public static void copyKeepValue(Object source, Object target) {
        String[] names = getNullPropertyNames(source);
        BeanUtils.copyProperties(source, target, names);
    }

    public static String[] getNullPropertyNames(Object source) {
        final BeanWrapper src = new BeanWrapperImpl(source);
        PropertyDescriptor[] pds = src.getPropertyDescriptors();
        Set<String> emptyNames = new HashSet<String>();
        for (PropertyDescriptor pd : pds) {
            Object srcValue = src.getPropertyValue(pd.getName());
            if (srcValue == null) emptyNames.add(pd.getName());
        }
        String[] result = new String[emptyNames.size()];
        return emptyNames.toArray(result);
    }

//    public static <T> List<T> copyList(List<?> sourceList, Class<T> target) {
//        return sourceList.stream().map(s -> copy(s, target)).collect(Collectors.toList());
//    }
//
//    public static <T> Set<T> copySet(Set<?> sourceList, Class<T> target) {
//        return sourceList.stream().map(s -> copy(s, target)).collect(Collectors.toSet());
//    }
    //endregion
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值