1. 程式人生 > >java物件複製和屬性值複製工具類

java物件複製和屬性值複製工具類

兩個不同型別的物件中有欄位名稱不區分大小寫的情況下一樣,欄位含義一樣,需要組裝到另一個物件中去,然後就寫了一個這種工具類
我的型別比較特殊,老系統和新系統的物件命名大小寫命名不一致,並且欄位相同型別也有不一致的情況,所以自己寫了一個,
不是很完美基本能用。

溫馨提示:
如果同一種類型的物件 屬性欄位名equals相等 並且型別一致。則完全可以用commons-beanutils包或者spring包中
的BeanUtils工具類中的copey屬性方法。

/**
 * 實體類欄位值相同的複製
 *
 * @author [email protected] 2017年8月18日
 */
public class CopyBeanUtil { static Logger log = LoggerFactory.getLogger(CopyBeanUtil.class); /** * 複製sour裡屬性不為空的值到obje為空的屬性 * * @param obje 目標實體類 * @param sour 源實體類 * @param isCover 是否保留obje類裡不為null的屬性值(true為保留源值,屬性為null則賦值) * @return obje */ public
static Object Copy(Object obje, Object sour, boolean isCover) { Field[] fields = sour.getClass().getDeclaredFields(); for (int i = 0, j = fields.length; i < j; i++) { String propertyName = fields[i].getName(); Object propertyValue = getProperty(sour, propertyName); if
(isCover) { if (getProperty(obje, propertyName) == null && propertyValue != null) { Object setProperty = setProperty(obje, propertyName, propertyValue); } } else { Object setProperty = setProperty(obje, propertyName, propertyValue); } } return obje; } /** * 複製sour裡屬性不為空的值到obj裡並相加 * * @param obj 目標實體類 * @param sour 源實體類 * @param isCover * @return obj */ public static Object CopyAndAdd(Object obj, Object sour, boolean isCover) { Field[] fields = sour.getClass().getDeclaredFields(); for (int i = 0, j = fields.length; i < j; i++) { String propertyName = fields[i].getName(); Object sourPropertyValue = getProperty(sour, propertyName); Object objPropertyValue = getProperty(obj, propertyName); if (isCover) { if (objPropertyValue == null && sourPropertyValue != null) { Object setProperty = setProperty(obj, propertyName, sourPropertyValue); } else if (objPropertyValue != null && sourPropertyValue == null) { Object setProperty = setProperty(obj, propertyName, objPropertyValue); } else if (objPropertyValue != null && sourPropertyValue != null) { Object setProperty = setProperty(obj, propertyName, ((int) sourPropertyValue) + (int) objPropertyValue); } } } return obj; } /** * 得到值 * * @param bean * @param propertyName * @return */ private static Object getProperty(Object bean, String propertyName) { Class clazz = bean.getClass(); try { Field field = clazz.getDeclaredField(propertyName); Method method = clazz.getDeclaredMethod(getGetterName(field.getName(),field.getType()), new Class[]{}); return method.invoke(bean, new Object[]{}); } catch (Exception e) { } return null; } /** * 給bean賦值 * * @param bean * @param propertyName * @param value * @return */ private static Object setProperty(Object bean, String propertyName, Object value) { Class clazz = bean.getClass(); try { Field field = clazz.getDeclaredField(propertyName); Method method = clazz.getDeclaredMethod(getSetterName(field.getName()), new Class[]{field.getType()}); return method.invoke(bean, new Object[]{value}); } catch (Exception e) { } return null; } /** * 根據變數名得到get方法 * * @param propertyName * @return */ private static String getGetterName(String propertyName) { String method ; if( propertyName.length()>1&& Character.isUpperCase(propertyName.charAt(1))){ method = "get" +propertyName; }else{ method = "get" + propertyName.substring(0, 1).toUpperCase() + propertyName.substring(1); } return method; } /** * 根據變數名和型別獲取getter方法 * @param propertyName * @param type * @return */ private static String getGetterName(String propertyName, Class<?> type) { String method ; if(type==Boolean.class|| type==boolean.class){ if("is".equalsIgnoreCase(propertyName.substring(0, 2))){ return propertyName; }else{ return "is" + propertyName.substring(0, 1).toUpperCase() + propertyName.substring(1); } } if( propertyName.length()>1&& Character.isUpperCase(propertyName.charAt(1))){ method = "get" +propertyName; }else{ method = "get" + propertyName.substring(0, 1).toUpperCase() + propertyName.substring(1); } return method; } /** * 得到setter方法 * * @param propertyName 變數名 * @return */ private static String getSetterName(String propertyName) { // String method = "set" + propertyName.substring(0, 1).toUpperCase() + propertyName.substring(1); String method ; if( propertyName.length()>1&& Character.isUpperCase(propertyName.charAt(1))){ method = "set" +propertyName; }else{ method = "set" + propertyName.substring(0, 1).toUpperCase() + propertyName.substring(1); } return method; } /** * 父類集合轉成子類集合集合通用方法(子類集合接收父類集合) * * @param list 父類集合 * @param <T> 子類 * @param <E> 父類 * @return */ public static <T, E> List<T> chang2ChildClassList(List<E> list) { List<T> alist = new ArrayList<>(); for (E o : list) { alist.add((T) o); } return alist; } /** * 屬性copy 複製sour裡屬性和obje裡屬性值忽略大小寫相同的 ,不為空的值賦值到obje裡 * 如果存在屬性複雜型別併為有效值慎用或改進 * * @param obje * @param sour * @param isCover 是否保留obje裡面屬性值不為空的欄位值 * @return */ public static Object copyByIgnoreCase(Object obje, Object sour, boolean isCover) { try { Field[] objFields = obje.getClass().getDeclaredFields(); Field[] sourFields = sour.getClass().getDeclaredFields(); for (int i = 0; i < sourFields.length; i++) { String sourPropertyName = sourFields[i].getName(); //獲取來源物件的屬性值 Object propertyValue = getSourPropertyValue(sour, sourPropertyName); for (int j = 0; j < objFields.length; j++) { try { String objPropertyName = objFields[j].getName(); if (objPropertyName.equalsIgnoreCase(sourPropertyName)) { if (isCover) { if (getProperty(obje, objPropertyName) == null && propertyValue != null) { setObjProperty(obje, objPropertyName, propertyValue); } } else { setObjProperty(obje, objPropertyName, propertyValue); } break; } } catch (Exception e) { log.error("給目標bean賦值出錯,objPropertyName:{},value:{}",sourPropertyName,propertyValue,e); e.printStackTrace(); } } } } catch (SecurityException e) { e.printStackTrace(); log.error("給目標bean賦值出錯,obje:{},sour:{}", JSON.toJSONString(obje), JSON.toJSONString(sour),e); } return obje; } /** * 根據屬性名獲取的值 * * @param sourceBean * @param sourcePropertyName * @return */ private static Object getSourPropertyValue(Object sourceBean, String sourcePropertyName) { Class clazz = sourceBean.getClass(); try { Field field = clazz.getDeclaredField(sourcePropertyName); Method method = clazz.getDeclaredMethod(getGetterName(field.getName(),field.getType()), new Class[]{}); return method.invoke(sourceBean, new Object[]{}); } catch (Exception e) { log.error("獲取屬性名(不區分大小寫)相似的值賦值出差", e); } return null; } /** * 給目標bean賦值 * * @param objBean * @param sourcePropertyName * @param value * @return */ private static Object setObjPropertyBySourceProperty(Object objBean, String sourcePropertyName, Object value) { Class clazz = objBean.getClass(); Field[] fields = clazz.getDeclaredFields(); try { for (int i = 0, j = fields.length; i < j; i++) { String propertyName = fields[i].getName(); if (sourcePropertyName.equalsIgnoreCase(propertyName)) { Field field = clazz.getDeclaredField(propertyName); if (field.getType() == BigDecimal.class) { if (value instanceof String) { value = new BigDecimal(String.valueOf(value)); } else if (value instanceof Integer || value instanceof Double) { // 傳double直接new BigDecimal,數會變大 value = BigDecimal.valueOf(Double.parseDouble(String.valueOf(value))); } } if (field.getType() == Double.class || field.getType() == double.class) { if (value instanceof BigDecimal) { DecimalFormat df = new DecimalFormat("#.000000"); Double v = Double.parseDouble(String.valueOf(value)); value = df.format(v); } } Method method = clazz.getDeclaredMethod(getSetterName(field.getName()), new Class[]{field.getType()}); return method.invoke(objBean, new Object[]{value}); } } } catch (Exception e) { } return null; } /** * 給目標bean賦值 * * @param objBean * @param propertyName * @param value * @return */ private static Object setObjProperty(Object objBean, String propertyName, Object value) { Class clazz = objBean.getClass(); try { Field field = clazz.getDeclaredField(propertyName); if (field.getType() == BigDecimal.class) { if (value instanceof String) { value = new BigDecimal(String.valueOf(value)); } else if (value instanceof Integer || value instanceof Double) { // 傳double直接new BigDecimal,數會變大 value = BigDecimal.valueOf(Double.parseDouble(String.valueOf(value))); } } if (field.getType() == Double.class || field.getType() == double.class) { if (value instanceof BigDecimal) { DecimalFormat df = new DecimalFormat("#.000000"); Double v = Double.parseDouble(String.valueOf(value)); value =new BigDecimal(df.format(v)); } } if (field.getType() == Integer.class || field.getType() == int.class) { if (value instanceof Float) { value = Math.round(Float.parseFloat(String.valueOf(value))); } } Method method = clazz.getDeclaredMethod(getSetterName(field.getName()), new Class[]{field.getType()}); log.info("給目標bean賦值,propertyName:{},value:{}",propertyName,value); Object obj = method.invoke(objBean, new Object[]{value}); return obj; } catch (Exception e) { log.error("給目標bean賦值出錯,propertyName:{},value:{}",propertyName,value,e); } return null; } public static void main(String[] args) { // ReAlarmResult re= new ReAlarmResult(); // re.setAlarmContent("sdfsdfsd"); // re.setBlat(2.234343); // re.setBlon(34.34324); // ReAlarmResult s = new ReAlarmResult(); // s.setAlarmContent("222"); // copyByIgnoreCase(s,re,true); // System.out.printf(JSON.toJSONString(s)); // BeanUtils.copyProperties(); //BeanUtils.copyProperties(); } }