Search code examples
javareflectionrealm

Realm java, how to access RealmObject property by string (reflection)


I wanted to access the property of model by string via reflection like

Object o = ...; // The object you want to inspect
Class<?> c = o.getClass();

Field f = c.getField("myColor");
f.setAccessible(true);

String valueOfMyColor = (String) f.get(o);

But i was still getting error that the property doesn't exist. Then i found that RealmModel objects are wrapped with RealmProxy class so that could be the reason.

So question is, how to access RealmModel properties by string? Via reflection or another way.


Solution

  • You need to either call realmGet$fieldName() method, or your getters like getFieldName() method

    For example, I did this

    public static String getFieldThroughGetterAsStringTransform(Object target, String property) {
        try {
            Method method = target.getClass().getMethod("get" + StringUtils.capitalize(property));
            Object getResult = method.invoke(target);
            return getResult != null ? getResult.toString() : null;
        } catch(Exception e) {
            Log.e(TAG, "Failed to map property [" + property + "] on object [" + target + "]");
            throw new RuntimeException(e);
        }
    }
    

    And

    String fieldValue = FieldTransformer.getFieldThroughGetterAsStringTransform(managedObject, fieldName);
    

    But you can look at other ways of calling getter, like Apache Commons BeanUtils:

    Object value = PropertyUtils.getProperty(person, "name");