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?
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>
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With