Realm java,如何通过字符串访问RealmObject属性(反射)

问题描述 投票:0回答:2

我想通过反射来访问模型的属性

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

但我仍然得到该财产不存在的错误。然后我发现RealmModel对象用RealmProxy类包装,这可能就是原因。

问题是,如何通过字符串访问RealmModel属性?通过反射或其他方式。

java reflection realm
2个回答
2
投票

您需要调用realmGet$fieldName()方法,或者像getFieldName()方法那样调用getter

例如,我这样做了

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

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

但你可以看看other ways of calling getter,就像Apache Commons BeanUtils:

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

1
投票

我更喜欢copyFromRealm这个对象并将其反映为常规对象

© www.soinside.com 2019 - 2024. All rights reserved.