開發過程中經常會遇到全量修改的場景,但好多時候在只修改一兩個屬性的時候會遇到不能快捷的對修改的屬性賦值的問題,
這邊基於 在京奮鬥者 的一篇博文中得到啓發,修改了部分代碼,寫出了這樣一個可以根據屬性是否爲空來自動賦值的工具類
,並以文記錄,希望幫助到更多人。
/**
* 複製修改對象方法
*
* 將原始完整對象的屬性
* 賦值給部分修改對象中爲空的屬性
*
* @param source 原始完整對象
* @param dest 部分修改對象
* @throws Exception
*/
public static void Copy(Object source, Object dest) throws Exception {
// 獲取屬性
BeanInfo sourceBean = Introspector.getBeanInfo(source.getClass(), Object.class);
PropertyDescriptor[] sourceProperty = sourceBean.getPropertyDescriptors();
BeanInfo destBean = Introspector.getBeanInfo(dest.getClass(), Object.class);
PropertyDescriptor[] destProperty = destBean.getPropertyDescriptors();
try {
for (int i = 0; i < sourceProperty.length; i++) {
for (int j = 0; j < destProperty.length; j++) {
if (sourceProperty[i].getName().equals(destProperty[j].getName()) && sourceProperty[i].getPropertyType() == destProperty[j].getPropertyType()) {
// 調用source的getter方法和dest的setter方法
if (destProperty[j].getReadMethod().invoke(dest) == null) {
destProperty[j].getWriteMethod().invoke(dest, sourceProperty[i].getReadMethod().invoke(source));
break;
}
}
}
}
} catch (Exception e) {
throw new Exception("屬性複製失敗:" + e.getMessage());
}
}
測試過程及結果: