Search code examples
javarealm

Finding the Java class for a given Realm schema


On a Realm object, I call getSchema().getAll() to obtain the available schemas, and then getClassName() on a schema to get its name.

How can I subsequently read that schema's data, i.e. the query the Java objects it holds? I have tried calling where(<class>).findAll() on the Realm object, but where() expects an argument whose type is the Java class in question, and I have not found a way to determine that class given only the schema name. Note that RealmObjectSchema.getClassName returns an unqualified name that doesn't fit this purpose.

So basically the question is how to find the Java class that corresponds to a schema. The information is there, as I can see from the classToTable and classToSchema fields in RealmSchema.

Or maybe where().findAll() isn't the best approach to retrieve the data?


Solution

  • Well a possibility would be to rely on some package internal API, the RealmProxyMediator to obtain the classes:

    RealmProxyMediator mediator = realm.configuration.getSchemaMediator();
    final Set<Class<? extends RealmModel>> modelClasses = mediator.getModelClasses();
    

    But according to the Realm 0.88.0 change log:

    Removed RealmConfiguration.getSchemaMediator() from public API which was deprecated in 0.86.0. Please use RealmConfiguration.getRealmObjectClasses() to obtain the set of model classes (#1797).

    So just use RealmConfiguration.getRealmObjectClasses().

    getRealmObjectClasses()

    public Set<Class<? extends RealmModel>> getRealmObjectClasses():

    Returns the unmodifiable Set of model classes that make up the schema for this Realm.

    Then you can just iterate that and use the classes returned in the set for your where(class) parameter.