PropertyUtils屬性拷貝方便好用

BeanUtils.copyProperties(Dest,Orig)的不足 與 PropertyUtils

常常須要進行bean之間的數值 拷貝,這會用到BeanUtils.copyProperties方法,可是在頁面上的checkbox爲空的時候傳的值是null,而通過 BeanUtils.copyProperties(DestBean,OrigBean)的拷貝,會把null設置爲false,可是若是需求是這樣 的:DestBean傳null表明不給server傳值,而傳false表明把server數據改成false,這樣顯然 BeanUtils.copyProperties(Dest,Orig)方法就不太好用了,能夠本身寫一個方法:public static ActionForm updateFields(ActionForm dest, ActionBean source, List fieldList) {    for (int i = 0; i < fieldList.size(); i++)    {      String name = (String) fieldList.get(i);      Object value = PropertyUtils.getProperty(source, name);      PropertyUtils.setProperty(dest, name, value);      Object destvalue = PropertyUtils.getProperty(dest, name);       }    return dest; } 便可完成兩個bean之間根據field list來相互賦值 其實根本不用本身寫一個方法,直接用PropertyUtils就能夠實現。若是checkbox值是null,那麼傳過去不會是false,而是null 兩個bean 之間拷貝值,最笨的方法就是a.setXXX(b.getXXX())而後想到用java反射去找到各個字段,而後一個循環就能夠實現bean的拷貝。可還有更加簡便的方法,用PropertyUtils。import org.apache.commons.beanutils.PropertyUtils;try{        PropertyUtils.copyProperties(b, a);       }   catch(Exception e){      }
相關文章
相關標籤/搜索