public static Object copyProperties(JSONObject oriObj, Object desObj) { //1. 首先要拿到oriObj对象的所有存在值不为空的键-值,放入到集合当中 Class desC = desObj.getClass(); Field[] desFields=desC.getDeclaredFields(); for (Map.Entry<String, Object> entry:oriObj.entrySet()){ String fieldName = entry.getKey(); Object value = entry.getValue(); Class<?> type = value.getClass();//字段的类型 String getMethodName="get"+fieldName.substring(0,1).toUpperCase()+fieldName.substring(1,fieldName.length()); try { if(value!=null){ //此处需要进行比对desObj中是否存在有相同名称的key for (Field desField:desFields) { //如果被替换对象中值不为空, 则跳过 if(desField.getName().equals(fieldName)){ if( value instanceof JSONObject ){ Method getMethod2 = desC.getMethod(getMethodName,null); Object o =getMethod2.invoke(desObj); copyProperties((JSONObject) value, o ); } else { String setMethodName = "set" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1, fieldName.length()); Method setMethod = null; setMethod = desC.getMethod(setMethodName, desField.getType()); setMethod.invoke(desObj, value); } // Method getMethod2 = desC.getMethod(getMethodName,null); // Object value2=getMethod2.invoke(o);//获取得到该属性的取值 // if(value2 != null ){ // continue; // } //2. 对desObj的键值进行赋值操作 } } } } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } catch (NoSuchMethodException e) { e.printStackTrace(); } } return desObj; }
标签:复杂,对象,Object,value,JSON,fieldName,desObj,null,desC From: https://www.cnblogs.com/heshana/p/16738678.html