beanutils.copyProperties()的使用总结

首先看一下,BeanUtils.copProperties的方法源码:

abstract class BeanUtils中代码整体分四段截图,去除图片之间的空格就是完整的源码:

上面截图主要的方法操作:

         for (PropertyDescriptor targetPd : targetPds) {
        //获取字段的写方法,--set
            Method writeMethod = targetPd.getWriteMethod();
       //如果方法不为空,且没有忽略
            if (writeMethod != null && (ignoreList == null || (!ignoreList.contains(targetPd.getName())))) {
        //获取原对象的字段
                PropertyDescriptor sourcePd = getPropertyDescriptor(source.getClass(), targetPd.getName());
                if (sourcePd != null) {
                //如果原对象的字段是存在的,获取原对象的这个字段的get方法
                    Method readMethod = sourcePd.getReadMethod();
                    if (readMethod != null &&
                //判断源对象的get的返回值类型和目标对象的set参数是否一致
                    ClassUtils.isAssignable(writeMethod.getParameterTypes()[0], readMethod.getReturnType())) {
                        try {
                        //如果类型一致再判断方法是不是public修饰的
                            if (!Modifier.isPublic(readMethod.getDeclaringClass().getModifiers())) {
                                //如果不是就强制反射
                                readMethod.setAccessible(true);
                            }
                        //然后获取值
                            Object value = readMethod.invoke(source);
                            if (!Modifier.isPublic(writeMethod.getDeclaringClass().getModifiers())) {
                                writeMethod.setAccessible(true);
                            }    
                                //赋值
                            writeMethod.invoke(target, value);
                        }
                        catch (Throwable ex) {
                            throw new FatalBeanException(
                                "Could not copy property '" + targetPd.getName() + "' from source to target", ex);
                        }
                    }
                }
            }
        }

1.属性名一一对应相同情况下,source的bean将覆盖掉目标bean对应的属性值。

bean A                                          bean B

结果:

 

当A类中(source中)有属性值为null的时候:

A类中的address的值为null。

结果:

结论:来源bean中值为null的属性在完成copyPoperties操作后,目标bean中对应的参数值也会变成null

 

2.属性名一一对应相同,参数类型不同。

bean A 中 phone 为String类型                           bean B 中 phone 为int类型 

结果:目标bean B中参数值不受影响,方法copy的前提是参数的类型也要对应相同。:

 

3.属性名大小写问题。

A类中的变量名大写                                    B类中的变量名小写 

相当于参数名不同,找不到参数,所以无法copy成功:

 

4.支持数组,集合

数组:

成功将b中数组类型参数的值改变:

在A,B类中各加入Map类型参数。

同样也成功了:


 

加入list类型参数之后:

最后也成功了:

  • 8
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值