将JSONObject中的值赋值给类中的同名属性 public Object addPropertyVale(JSONObject data, Object entity)throws IllegalArgumentException, IllegalAccessException {Field fields[] = entity.getClass().getDeclaredFields();for (Map.Entry
public Object addPropertyVale(JSONObject data, Object entity) throws IllegalArgumentException, IllegalAccessException { Field fields[] = entity.getClass().getDeclaredFields(); for (Map.Entry将一个类中的属性值赋值给另一个类中同名属性entry : data.entrySet()) { for (int i = 0; i < fields.length; i++) { fields[i].setAccessible(true); if (fields[i].getName().equals(entry.getKey())) {// json字段key和对象实体属性名相同 // 将value赋值给属性 if (fields[i].getGenericType().getTypeName().equals("java.lang.String")) { fields[i].set(entity, data.getString(entry.getKey())); } if (fields[i].getGenericType().getTypeName().equals("java.lang.Integer")) { fields[i].set(entity, data.getInteger(entry.getKey())); } if (fields[i].getGenericType().getTypeName().equals("java.lang.Long")) { fields[i].set(entity, data.getLong(entry.getKey())); } if (fields[i].getGenericType().getTypeName().equals("int")) { fields[i].set(entity, data.getInteger(entry.getKey())); } if (fields[i].getGenericType().getTypeName().equals("long")) { fields[i].set(entity, data.getLong(entry.getKey())); } if (fields[i].getGenericType().getTypeName().equals("java.lang.Boolean")) { fields[i].set(entity, data.getBoolean(entry.getKey())); } } } }
public Object addPropertyVale(Object editEntity, Object entity) { Field fieldEdit[] = editEntity.getClass().getDeclaredFields(); Field field[] = entity.getClass().getDeclaredFields(); for (int i = 0; i < fieldEdit.length; i++) { fieldEdit[i].setAccessible(true); for (int j = 0; j < field.length; j++) { field[j].setAccessible(true); if (fieldEdit[i].getName().equals(field[j].getName()) && field[i].getName() != "id") {// id不能修改 try { field[j].set(entity, fieldEdit[i].get(editEntity)); } catch (IllegalArgumentException | IllegalAccessException e) { e.printStackTrace(); } } } } return entity; }