I try to create class with generic type where I create function to read list of entities. And I know that I have 2 ways to do this: (#1) by read each entity in a loop or (#2) create a map of entities directly.
2nd way looks more efficient but unfortunately GenericTypeIndicator
doesn't work with generic type - it returns IllegalStateException: Unknown type encountered: T
when I use it in code:
Map<String, T> entityMap =
dataSnapshot.getValue(new GenericTypeIndicator<Map<String, T>>() {});
So:
public class SomeClass<T extends KeyEntity> {
private final Class<T> mGenericClass;
private final String mRefKey;
public SomeClass(Class<T> clazz, String refKey) {
mGenericClass = clazz;
mRefKey = refKey;
}
public class KeyEntity {
private String mKey;
public KeyEntity() {}
public String getKey() {
return mKey;
}
public void setKey(String key) {
mKey = key;
}
}
public interface EntityListListener<T> {
abstract public void onEntityListLoaded(List<T> entity);
}
public void loadAll(final EntityListListener<T> entityListListener) {
DatabaseReference dbRef = FireDbUtils.getReference(mRefKey);
dbRef.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
List<T> entityList = new ArrayList<>((int) dataSnapshot.getChildrenCount());
// #1 - read each entity in a loop
for (DataSnapshot childSnapshot : dataSnapshot.getChildren()) {
T entity = dataSnapshot.getValue(mGenericClass);
entity.setKey(childSnapshot.getKey());
entityList.add(entity);
}
// #2 - read all entity into a map
// GenericTypeIndicator doesn't like generic type
// if used, it returns "IllegalStateException: Unknown type encountered: T"
Map<String, T> entityMap
= dataSnapshot.getValue(new GenericTypeIndicator<Map<String, T>>() {});
for (Map.Entry<String, T> pair : entityMap.entrySet()) {
T entity = pair.getValue();
entity.setKey(pair.getKey());
entityList.add(entity);
}
entityListListener.onEntityListLoaded(entityList);
}
@Override
public void onCancelled(DatabaseError databaseError) {}
});
}
eg. data:
{
carList: {
carKey1: {
name: "wife car"
},
carKey2: {
name: "my best car in the world ever"
}
},
garageList: {
garageKey1: {
name: "house garage"
},
garageKey2: {
name: "top secret garage under main garage"
}
}
}
Use ParameterizedType to find a generic class object
ParameterizedType type = (ParameterizedType)this.getClass().getGenericSuperclass();
//all generic classes
Type[] args = type.getActualTypeArguments();
Class<T> genericClass = (Class<T>) args[0];
T entity = dataSnapshot.getValue(genericClass);
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