title: Best practice for using generics with Firebase snapshot.getValue()
body: <p><strong>TL;DR: How to correctly use a generic class with Firebase DataSnapshot.getValue()?</strong></p>
  
  <p>Use case: I want to implement a single generic remote datasource class for all my entities (a bunch of them) using Firebase. When listening to data change, I want to get the values from datasnapshot as an object of type E (its type determined elsewhere) but I don't know if it is doable with Firebase query, like the following:</p>
  
  <pre><code>public class GenRemoteDataSource&lt;E extends SomeClass&gt;
  {
     //...
     public void onDataChange(DataSnapshot dataSnapshot)
     {
          E item = (E) dataSnapshot.getValue(); // &lt;- unchecked cast and it doesn't work
          items.add(item);
     }
  }
  </code></pre>
  
  <p>For example, I have a Foo class that extends SomeClass, and the implementation of this GenRemoteDataSource with a class of Foo would be:</p>
  
  <pre><code>public class Foo extends SomeClass{}
  
  public class FooRemoteDataSource extends GenRemoteDataSource&lt;Foo&gt;
  {
     //...
  }
  </code></pre>
  
  <p>but Firebase throws a runtime error because instead of casting the getValue() as Foo, it would try to cast value as a upper bound SomeClass instead. I'm baffled as to why this happens:</p>
  
  <pre><code>Java.lang.ClassCastException: java.util.HashMap cannot be cast to com.example.app.SomeClass
  </code></pre>
  
  <p>please advise on how should I do this with Type-safety (No unchecked cast) . Thank you.</p>
  
  <p><strong>EDIT</strong> Stuff turned out to be irrelevant down below, see <a href="https://firebase.google.com/docs/reference/android/com/google/firebase/database/GenericTypeIndicator" rel="nofollow noreferrer">GenericTypeIndicator</a></p>
  
  <p><strike>
  <strong>EDIT</strong>
  I've also tried (blindly and heck worth a try) the GenericTypeIndicator,</p>
  
  <pre><code>GenericTypeIndicator&lt;E&gt; mTypeIndicator = new GenericTypeIndicator&lt;&gt;();
  E item = dataSnapshot.getValue(mTypeIndicator);
  </code></pre>
  
  <p>but it instead spits the following runtime error.</p>
  
  <pre><code>com.google.firebase.database.DatabaseException: Not a direct subclass of GenericTypeIndicator: class java.lang.Object
  </code></pre>
  
  <p></strike></p>