1. 程式人生 > >java不同物件屬性賦值

java不同物件屬性賦值

將JSONObject中的值賦值給類中和key同名的屬性

public Object addPropertyVale(JSONObject data, Object entity)
            throws IllegalArgumentException, IllegalAccessException {

        Field fields[] = entity.getClass().getDeclaredFields();
        for (Map.Entry<String, Object> 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())); } } } } return entity; }

傳入兩個類,將editEntity類中和entity類中同名屬性賦值給另一個類

    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;
    }