BeanUtils.copyProperties復(fù)制屬性失敗的原因及解決方案
BeanUtils.copyProperties復(fù)制屬性失敗
描述
在JavaE中使用 BeanUtils.copyProperties,把A對象的name、age等屬性復(fù)制到B對象中,A與B對象的類型不同。出現(xiàn)的問題是復(fù)制屬性失敗,根本原因是 BeanUtils找不到set、get方法。
import org.springframework.beans.BeanUtils; BeanUtils.copyProperties(one, monitorCount);
解決辦法
1,為復(fù)制對象的屬性增加set、get方法。比如給name、age屬性增加set、get方法。
2,也可以使用插件生成setter、getter比如:
package com.css.oa.exam.monitor.bean;
import lombok.Data; //使用lombok插件
@Data //使用這個注解可以生成setter
public class AssignOne{
public String name;
public String age;
}
BeanUtils.copyProperties應(yīng)用的改進(jìn)
在MVC的開發(fā)模式中經(jīng)常需要將model與pojo的數(shù)據(jù)綁定,apache和spring的工具包中都有BeanUtils,使用其中的copyProperties方法可以非常方便的進(jìn)行這些工作,但在實際應(yīng)用中發(fā)現(xiàn),對于null的處理不太符合個人的需要,例如在進(jìn)行修改操作中只需要對model中某一項進(jìn)行修改,那么一般我們在頁面上只提交model的ID及需要修改項的值,這個時候使用BeanUtils.copyProperties會將其他的null綁定到pojo中去。
為解決這個問題我重寫了部分spring BeanUtils的代碼
如下:
public abstract class BeanUtils extends org.springframework.beans.BeanUtils {
public static void copyProperties(Object source, Object target) throws BeansException {
Assert.notNull(source, "Source must not be null");
Assert.notNull(target, "Target must not be null");
Class<?> actualEditable = target.getClass();
PropertyDescriptor[] targetPds = getPropertyDescriptors(actualEditable);
for (PropertyDescriptor targetPd : targetPds) {
if (targetPd.getWriteMethod() != null) {
PropertyDescriptor sourcePd = getPropertyDescriptor(source.getClass(), targetPd.getName());
if (sourcePd != null && sourcePd.getReadMethod() != null) {
try {
Method readMethod = sourcePd.getReadMethod();
if (!Modifier.isPublic(readMethod.getDeclaringClass().getModifiers())) {
readMethod.setAccessible(true);
}
Object value = readMethod.invoke(source);
// 這里判斷以下value是否為空 當(dāng)然這里也能進(jìn)行一些特殊要求的處理 例如綁定時格式轉(zhuǎn)換等等
if (value != null) {
Method writeMethod = targetPd.getWriteMethod();
if (!Modifier.isPublic(writeMethod.getDeclaringClass().getModifiers())) {
writeMethod.setAccessible(true);
}
writeMethod.invoke(target, value);
}
} catch (Throwable ex) {
throw new FatalBeanException("Could not copy properties from source to target", ex);
}
}
}
}
}
}
apahce的BeanUtils的處理方法類似
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
@Transactional遇到try catch失效的問題
這篇文章主要介紹了@Transactional遇到try catch失效的問題及解決方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-01-01
IDEA無法識別相關(guān)module模塊問題的解決過程
這篇文章主要給大家介紹了關(guān)于IDEA無法識別相關(guān)module模塊問題的解決過程,文中通過圖文介紹的非常詳細(xì),對大家學(xué)習(xí)或者使用IDEA具有一定的參考借鑒價值,需要的朋友可以參考下2023-07-07
Redisson RedLock紅鎖加鎖實現(xiàn)過程及原理
本文主要介紹了Redis中Redisson紅鎖(Redlock)使用原理,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-02-02
Java持久化框架Hibernate與Mybatis優(yōu)劣及選擇詳解
這篇文章主要介紹了Java持久化框架Hibernate與Mybatis優(yōu)劣及選擇詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-05-05

