1

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.

luky
  • 2,263
  • 3
  • 22
  • 40

2 Answers2

3

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");
Community
  • 1
  • 1
EpicPandaForce
  • 79,669
  • 27
  • 256
  • 428
  • bit messy but thx, btw you know how is it possible that in code works the access on original RealmObject properties but via reflection not? if it works in code it must works also via reflection? – luky Nov 30 '16 at 08:39
  • 1
    Because the field is null, the getters call a native method of the proxy that reads from the Realm directly – EpicPandaForce Nov 30 '16 at 09:16
1

i prefer to copyFromRealm this object and reflect it as regular object

itzhar
  • 12,743
  • 6
  • 56
  • 63