TruMan1
TruMan1

Reputation: 36178

How do I use Realm with generic type?

I have a generic method and would like to retrieve objects using the generic type. This is my method:

public static <T extends RealmObject & IndentifierModel> void storeNewData() {
  ...
  T item = realm.where(Class<T>) // Not compiling (Expression not expected)
    .equalTo("ID", data.get(i).getID())
    .findFirst();
}

The above isn't working for realm.where(Class<T>). How do I pass in my generic type to Realm?

Upvotes: 5

Views: 3438

Answers (1)

Vivin Paliath
Vivin Paliath

Reputation: 95598

You have to supply the generic parameter like so:

public static <T extends RealmObject & IndentifierModel> void storeNewData(Class<T> clazz) {
  T item = realm.where(clazz) 
    .equalTo("ID", 123)
    .findFirst();
}

Class<T> is not valid, since that's like saying realm.where(Class<List<String>>) or realm.where(Class<String>). What you need is an actual Class<T> instance. But you cannot use T.class either since T is not available at runtime due to type-erasure. At runtime, the method basically needs a Class<T> instance to work properly. Since you cannot get that from T, you will have to explicitly supply an argument of type Class<T>.

Upvotes: 13

Related Questions