copyproperties爆红_BeanUtils.copyProperties复制失败探究
一?BeanUtils.copyProperties是什么
BeanUtils類全路徑為org.springframework.beans.BeanUtils是spring-beans包下的一個用于bean相關(guān)工具類。
BeanUtils.copyProperties(Object source, Object target)這個方法的作用是 把source這個bean的全部屬性值 復(fù)制到?target這個bean對象
二 遇到問題BeanUtils.copyProperties(Object source, Object target)寫入失敗
source和 target 是兩個不同類的對象,屬性名稱全都一樣,發(fā)現(xiàn)其它字段都拷貝成功,但是有一個字段沒有拷貝復(fù)制過來
仔細(xì)檢查發(fā)現(xiàn):該拷貝失敗字段的類型不一樣,一個是int類型 一個是String類型,
懷疑:source對象和target對象相應(yīng)屬性的名稱和類型必須都一樣才可以成功拷貝屬性值,
經(jīng)過修改測試發(fā)現(xiàn),親測有效,?下面閱讀源代碼進(jìn)行確認(rèn)原因。
三 閱讀源碼
private static void copyProperties(Object source, Object target, Class> editable, String... ignoreProperties)
throws BeansException {
Assert.notNull(source, "Source must not be null");
Assert.notNull(target, "Target must not be null");
Class> actualEditable = target.getClass();
if (editable != null) {
if (!editable.isInstance(target)) {
throw new IllegalArgumentException("Target class [" + target.getClass().getName() +
"] not assignable to Editable class [" + editable.getName() + "]");
}
actualEditable = editable;
}
PropertyDescriptor[] targetPds = getPropertyDescriptors(actualEditable);
List ignoreList = (ignoreProperties != null ? Arrays.asList(ignoreProperties) : null);
for (PropertyDescriptor targetPd : targetPds) {
Method writeMethod = targetPd.getWriteMethod();
if (writeMethod != null && (ignoreList == null || !ignoreList.contains(targetPd.getName()))) {
PropertyDescriptor sourcePd = getPropertyDescriptor(source.getClass(), targetPd.getName());
if (sourcePd != null) {
Method readMethod = sourcePd.getReadMethod();
if (readMethod != null && ClassUtils.isAssignable(writeMethod.getParameterTypes()[0], readMethod.getReturnType())) {
try {
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);
}
}
}
}
}
}
spring代碼解釋說明:
writeMethod 即相關(guān)屬性的setXX方法,readMethod即 相關(guān)屬性的getXX方法
ClassUtils.isAssignable(Class> lhsType, Class> rhsType)是否可以轉(zhuǎn)成某個類型,根據(jù)返回值 true/false來判斷 rhsType 是不是 lhsType
根據(jù)代碼可以看到,依次遍歷target的全部field屬性,判斷該屬性在target中setXX方法的參數(shù)類型和 source中g(shù)etXX方法的返回值類型是否一致,
如果不一致則返回,如果一致則:從source對象中通過getXX得到屬性值value,再通過target該屬性的set方法,把value值set進(jìn)去。
四?BeanUtils.copyProperties使用總結(jié)
BeanUtils.copyProperties(Object source, Object target)方法,source對象和target對象相應(yīng)屬性的名稱和類型必須都一樣才可以成功拷貝屬性值
BeanUtils.copyProperties只對bean屬性進(jìn)行復(fù)制,這里的復(fù)制屬于淺復(fù)制。BeanUtils.copyProperties利用反射,直接將對象的引用set進(jìn)去,并不是深拷貝。
總結(jié)
以上是生活随笔為你收集整理的copyproperties爆红_BeanUtils.copyProperties复制失败探究的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: matlab画倾斜的椭球,在MATLAB
- 下一篇: efcore调用函数_如何在EF Cor