第一步: BeanUtils.copyProperties()與PropertyUtils.copyProperties() 1、 通過反射將一個對象的值賦值個另外一個對象(前提是對象中屬性的名字相同)。 2、 BeanUtils.copyProperties(obj1,obj2); 經常鬧混不知道是誰給誰賦值,無意中先到"后付前"這個詞來幫助自己記憶這個功能。即將obj2的值賦值給obj1。 3、 如果2中實例obj2為空對象,即值new了他的實例並沒有賦值的話obj1對應的屬性值也會被設置為空置。 4、BeanUtils與PropertyUtils對比(這里對比copyProperties方法) PropertyUtils的copyProperties()方法幾乎與BeanUtils.copyProperties()相同,主要的區別在於后者提供類型轉換功能,即發現兩個JavaBean的同名屬性為不同類型時,在支持的數據類型范圍內進行轉換,BeanUtils 不支持這個功能,但是BeanUtils速度會更快一些。 主要支持轉換類型如下: * java.lang.BigDecimal * java.lang.BigInteger * boolean and java.lang.Boolean * byte and java.lang.Byte * char and java.lang.Character * java.lang.Class * double and java.lang.Double * float and java.lang.Float * int and java.lang.Integer * long and java.lang.Long * short and java.lang.Short * java.lang.String * java.sql.Date * java.sql.Time * java.sql.Timestamp 不支持java.util.Date轉換,但支持java.sql.Date。如果開發中Date類型采用util而非sql.Date程序會拋出argument mistype異常。 2 第二步:擴展BeanUtils支持時間類型轉換 import java.lang.reflect.InvocationTargetException; import org.apache.commons.beanutils.BeanUtils; import org.apache.commons.beanutils.ConvertUtils; /** * 重寫BeanUtils.copyProperties * * @author monkey */ public class BeanUtilsExtends extends BeanUtils { static { ConvertUtils.register(new DateConvert(), java.util.Date.class); ConvertUtils.register(new DateConvert(), java.sql.Date.class); } public static void copyProperties(Object dest, Object orig) { try { BeanUtils.copyProperties(dest, orig); } catch (IllegalAccessException ex) { ex.printStackTrace(); } catch (InvocationTargetException ex) { ex.printStackTrace(); } } } import java.text.ParseException; import java.text.SimpleDateFormat; import org.apache.commons.beanutils.Converter; /** * 重寫日期轉換 * * @author houzhiqing */ public class DateConvert implements Converter { public Object convert(Class arg0, Object arg1) { String p = (String) arg1; if (p == null || p.trim().length() == 0) { return null; } try { SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); return df.parse(p.trim()); } catch (Exception e) { try { SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd"); return df.parse(p.trim()); } catch (ParseException ex) { return null; } } } }
