描述:新bean和旧bean拥有相同的字段属性。将旧bean的属性值,赋给新bean。
Java代码如下:
1 /** 2 * 反射Bean 3 * @param bean 反射的对象 4 * @param newBean 要反射的新对象 5 * @throws Exception 6 */ 7 public void injectValueBean2Bean(Object bean, Object newBean) throws Exception { 8 try { 9 Field[] fields = newBean.getClass().getDeclaredFields(); 10 for (int i = 0; i < fields.length; i++) { 11 fields[i].setAccessible(true); 12 String fieldName = fields[i].getName(); 13 String method=""; 14 if ("CHGLIST".equals(fieldName)){ 15 continue; 16 } 17 if("FLTID".equals(fieldName)){ 18 method="getFltId"; 19 }else if("PARKINGBAY".equals(fieldName)){ 20 method="getParkingBay"; 21 }else if("DEPARTURECORRIDOR".equals(fieldName)){ 22 method="getDepartureCorridor"; 23 }else{ 24 method= "get" + fieldName.substring(0,1)+fieldName.substring(1).toLowerCase(); 25 } 26 String value=(String) bean.getClass().getMethod(method).invoke(bean); 27 if(StringUtils.isEmpty(value)){ 28 value=""; 29 } 30 fields[i].set(newBean,value); 31 } 32 } catch (Exception e) { 33 throw new Exception(); 34 } 35 }
该方法会抛异常,要注意检查get方法的写法,和新旧bean字段是否一致。