Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 898
TruMan1 Avatar asked Dec 11 '22 22:12

TruMan1


1 Answers

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>.

like image 184
Vivin Paliath Avatar answered Dec 29 '22 12:12

Vivin Paliath