Java对象拷贝工具(超级好用!!!!!)

git地址,欢迎来star

https://github.com/sun-junchen/data-utils

data 工具,目前实现了拷贝

package com.example.entity;

import com.example.common.ErrorCode;
import com.example.exception.BusinessException;
import org.springframework.util.ReflectionUtils;

import java.lang.reflect.*;
import java.util.function.Consumer;
public interface BaseData {

    String GET = "get";
    String SET = "set";
    default <V> V asTargetObject(Class<V> clazz, Consumer<V> consumer) {
        V v = this.asTargetObject(clazz);
        consumer.accept(v);
        return v;
    }

    default <V> V asTargetObject(Class<V> clazz) {
        try {
            Field[] declaredFields = clazz.getDeclaredFields();
            Constructor<V> constructor = clazz.getConstructor();
            V v = constructor.newInstance();
            for (Field declaredField : declaredFields) convert(declaredField, v);
            return v;
        } catch (ReflectiveOperationException e) {
            throw new BusinessException(ErrorCode.CAST_OBJECT_ERROR);
        }

    }

    default void convert(Field field, Object vo) {

        try {
            Field source = this.getClass().getDeclaredField(field.getName());

            ReflectionUtils.makeAccessible(field);
            ReflectionUtils.makeAccessible(source);

            Method sourceGetter = this.getClass().getMethod(GET + capitalize(field.getName()));
            Method targetSetter = vo.getClass().getMethod(SET + capitalize(field.getName()), field.getType());
            Object value = sourceGetter.invoke(this);
            targetSetter.invoke(vo, value);
        } catch (NoSuchFieldException | InvocationTargetException | IllegalAccessException | NoSuchMethodException ignored) {
//              这里ignored 原因是
//              两个类的字段数量不一样的时候,会报 java.lang.NoSuchFieldException
//              但是多出来的字段我们是可以处理的
        }


    }

    default String capitalize(String str) {
        if (str == null || str.isEmpty()) {
            return str;
        }
        return Character.toUpperCase(str.charAt(0)) + str.substring(1);
    }
}

项目中有测试方法

  1. 实现对象深拷贝
  2. 实现对象Collection 深拷贝(List Set …)

实现步骤

  1. dto 实现 BaseData接口
  2. dto.asViewObject(Target.class);
  3. 如果 Target 还有其他字段 也可以自定义,例如githu项目测试用例中的genderNum(只是简单举的例子,按照项目实际来)
 AccountVO accountVO = accountDTO.asTargetObject(AccountVO.class,v->{
            v.setGenderNum(Objects.equals(accountDTO.getGender(), "男") ? "1" : "0");
        });

注意

两个类 相同的字段名的字段类型 必须完全一样!!!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

子仪_

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值