This library auto-generate helper classes that can help make Realm queries more type safe.
For each Realm model class a corresponding <class>Fields
class is created with static references
to all queryable field names.
Just include the following dependency in your gradle.build
file
apt 'dk.ilios:realmfieldnameshelper:1.1.0'
This library is compatible with Realm 1.1.1
and onwards.
The library adds an annotation processor that automatically detects all Realm model classes and
generated an extra class called <className>Fields
. This class will contain static references
to all field names that can be queried.
// Standard Realm Model class
public class Person extends RealmObject {
private String name;
private boolean hasDogs; // camel case naming gets converted to uppercase separated by "_"
private boolean mHasCats; // Hungarian notation is evil but support for m starting prefix.
private boolean has_fish; // fields already using "_" are just converted as they are.
private Dog favoriteDog; // linked fields are generated one link away
private RealmList<Dog> dogs; // linked fields are generated one link away
@Ignore
private int random;
// Getters and setters ...
}
public class Dog extends RealmObject {
private String name;
// Getters and setters ...
}
// This class is automatically generated by this library
public class PersonFields {
public static final String NAME = "name";
public static final String HAS_DOGS = "hasDogs";
public static final String HAS_CATS = "mHasCats";
public static final String HAS_FISH = "has_fish";
public static final class FAVORITE_DOG {
public static final String $ = "favoriteDog"; // field name in parent object
public static final String NAME = "favoriteDog.name";
}
public static final class DOGS {
public static final String $ = "dogs"; // field name in parent object
public static final String NAME = "dogs.name";
}
}
// And can be used when creating queries
Realm realm = Realm.getDefaultInstance();
RealmResults<Person> results = realm.where(Person.class)
.equalTo(PersonFields.NAME, "John")
.findAll();
RealmResults<Person> results = realm.where(Person.class)
.equalTo(PersonFields.FAVORITE_DOG.NAME, "Fido")
.findAll();
You can also see an example here.
Even though I am a contributor to Realm, this project is not officially affiliated with Realm and was created purely to scratch an itch in a side project I was working on.
Use it with that it mind.