首先看一下,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类型参数之后:
最后也成功了: