Realm не устанавливает значения для полей объектов на отражение (Android) - PullRequest
0 голосов
/ 29 сентября 2018

Я пытаюсь реализовать абстракцию для области, чтобы я мог сэкономить время при использовании операции CURD на БД.

абстракция, которую я строю, - controller для операции базы данных, чтобыЯ мог бы использовать это controller, которое выполняет операцию CURD с любой таблицей.

, то есть controller, о котором я говорю, это просто Java class имеет четыре метода create update read delete.

это create, который использует отражение для создания db objects и связывает поля переданного data object с этим db object

 /**
     * this method will delete the old data "you can change that"
     * of the table then store the passed data array in the table
     *
     * @param datum    the data Object you want to
     *                 save in the database
     * @param map      this map will contain which field
     *                 value in the data class will be
     *                 binded to which field in the db class
     *                 and will have this form dataFieldName => dbFieldName
     * @param callback when the function finish it's work it will
     *                 return a boolean value indicate whether
     *                 the function successfully finish it's work
     */
    public void create(
            Object datum,
            Class dataClass,
            HashMap<String, String> map,
            SaveDataCallback callback
    ) {
        Realm realm = Realm.getInstance(configuration);
        realm.executeTransactionAsync(bgRealm -> {
                    long id;

                    Number currentId = bgRealm.where(clacc).max("id");//the clacc object is passed in the constructor of the controller  
                    if (currentId == null)
                        id = 1;
                    else
                        id = currentId.longValue() + 1;

                    RealmObject dbObject = bgRealm.createObject(clacc, id++);//the clacc object is passed in the constructor of the controller 
                    mapObjects(datum, dataClass, dbObject, clacc, map);



                }
                , () -> callback.onSavingDataFinished(true)
                , error -> callback.onSavingDataFinished(false));
    }


private void mapObjects(
            Object source,
            Class sourceClass,
            Object destination,
            Class destinationClass,
            HashMap<String, String> map) {
        String[] sourceFieldNames = map.keySet().toArray(new String[map.size()]);

        try {

            for (int i = 0; i < map.size(); i++) {
                Field sourceField = sourceClass.getDeclaredField(sourceFieldNames[i]);
                sourceField.setAccessible(true);
                Object sourceValue = sourceField.get(source);

                String destinationFieldName = map.get(sourceFieldNames[i]);
                Field destinationField = destinationClass.getDeclaredField(destinationFieldName);
                destinationField.setAccessible(true);

                if (sourceField.getType() == Short.TYPE) {
                    destinationField.set(destination, Short.parseShort(sourceValue.toString()));
                    continue;
                }
                if (sourceField.getType() == Integer.TYPE) {
                    destinationField.set(destination, Integer.parseInt(sourceValue.toString()));
                    continue;
                }
                if (sourceField.getType() == Long.TYPE) {
                    destinationField.set(destination, Long.parseLong(sourceValue.toString()));
                    continue;
                }
                if (sourceField.getType() == Float.TYPE) {
                    destinationField.set(destination, Float.parseFloat(sourceValue.toString()));
                    continue;
                }
                if (sourceField.getType() == Double.TYPE) {
                    destinationField.set(destination, Double.parseDouble(sourceValue.toString()));
                    continue;
                }
                if (sourceField.getType() == Byte.TYPE) {
                    destinationField.set(destination, Byte.parseByte(sourceValue.toString()));
                    continue;
                }
                if (sourceField.getType() == Boolean.TYPE) {
                    destinationField.set(destination, Boolean.parseBoolean(sourceValue.toString()));
                    continue;
                }
                destinationField.set(destination, sourceValue);

            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

проблема заключается в следующем:

когда я пытаюсь запросить базу данных, чтобы получить объект после завершения процесса, база данных возвращает объекты, которые я создаю с помощью этой функции, но эти объекты не имеют данных actually the returned data is set to default value to each type i.e. string to null boolean to false etc...

мой вопрос:

есть ли проблема в моем коде или база данных области не поддерживает установку значений для объектов при отражении?

1 Ответ

0 голосов
/ 30 сентября 2018

Realm не поддерживает настройку поля значений управляемых объектов с помощью отражения.

Однако это будет работать, если вы вызываете методы сеттера с помощью отражения.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...