利用反射手写对象属性复制

因为在工作中经常用到 BeanUtils.copyProperties(userInfo, userInfoVO); 所以就想着试试看自己的反射水平怎么样?能不能自己也写个一样的功能?所以我就写了个如下方法,虽然在很多方面还需要优化,但是基本功能是实现了的。

public class BeanCopyTest {

    @Test
    public void beanCopyProperties()   {
        UserInfo userInfo = new UserInfo("admin", "123", 20, "admin@qqcom");
        UserInfoVO beanCopy = beanCopyProperty(userInfo, UserInfoVO.class);
        System.out.println(userInfo);
        // toString无法显示 如果是public的可以进行显示
        System.out.println(beanCopy);
        System.out.println(beanCopy.getAge()+","+beanCopy.getName()+","+beanCopy.getPassword()+","+beanCopy.getEmail());

    }

    @Test
    public void copyProperties(){
        UserInfo userInfo = new UserInfo("admin", "123", 20, "admin@qqcom");

        UserInfoVO userInfoVO = new UserInfoVO();
        BeanUtils.copyProperties(userInfo, userInfoVO);
        System.out.println(userInfoVO.getAge() + "," + userInfoVO.getName() + "," + userInfoVO.getPassword() + "," + userInfoVO.getEmail());
    }

    /***
     * <p>
     * beanCopyProperty :将源对象的属性复制到指定类型对象上,支持【直接继承】的方式,允许父类用private修饰
     * 需要注意的是,父类用private修饰的成员变量,子类无法在toString中访问,所有会导致赋值成功,但是toString无法打印
     * </p >
     * @param source 源对象
     * @param targetClazz 目标类class
     * @return T
     * @author compass
     * @date 2022/5/10 22:17
     * @since 1.0.0
     **/
    public static <T> T beanCopyProperty(Object source, Class<T> targetClazz)   {
        if (source == null || targetClazz == null){
            throw  new IllegalArgumentException("source or targetClazz is Not Null");
        }
        Field[] sourceFields = source.getClass().getDeclaredFields();
        Class<?> sourceClass = source.getClass();
        Object resultInstance = null;
        try {
            resultInstance = targetClazz.newInstance();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        List<Object> targetFiledNameList = new ArrayList<>();

        // 获取父类属性名称
        if (!(targetClazz.getSuperclass() == Object.class)) {
            Field[] targetParentFields = targetClazz.getSuperclass().getDeclaredFields();
            for (Field targetParentField : targetParentFields) {
                targetFiledNameList.add(targetParentField.getName());
            }
        }

        // 获取当前类属性名称
        Field[] targetFieldArr = targetClazz.getDeclaredFields();
        for (Field targetField : targetFieldArr) {
            if (!(targetFiledNameList.contains(targetField.getName())))
                targetFiledNameList.add(targetField.getName());
        }

        // 根据来源对象属性给目标对象属性赋值
        for (int i = 0; i < sourceFields.length; i++) {
            try {
                // 获取原本字段的value
                String sourceFieldName = sourceFields[i].getName();
                Field sourceField = sourceClass.getDeclaredField(sourceFieldName);
                sourceField.setAccessible(true);
                Object currentFiledValue = sourceField.get(source);

                // 根据属性名称给目标对象设置值
                Field targetField = null;
                if (targetFiledNameList.contains(sourceFieldName)) {
                    if (!(targetClazz.getSuperclass() == Object.class)) {
                        targetField = targetClazz.getSuperclass().getDeclaredField(sourceFieldName);
                    } else {
                        targetField = targetClazz.getDeclaredField(sourceFieldName);
                    }

                    targetField.setAccessible(true);
                    targetField.set(resultInstance, currentFiledValue);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return (T) resultInstance;
    }

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值