title: Generic type of class
body: <p>Is there a way to get the generic type of the following class at runtime (I will call <code>doSomething()</code> at runtime):</p>
  
  <pre><code>class MyClass&lt;D&gt; extends BaseClass&lt;List&lt;D&gt;&gt; {
  
      public Class&lt;D&gt; getGenericClass(){
          Type [] ta = ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments();
          Class ty = (Class) ta[0];   // is java.util.List&lt;D&gt; and throws a cast exception
  
         // TODO I want to know what kind of class "D" is
      }
  
  }
  
  class BaseClass&lt;T&gt;
     T data;
  }
  </code></pre>
  
  <p>I would like to use the <code>MyClass</code> as follows:</p>
  
  <pre><code>MyClass&lt;Foo&gt; instance = new MyClass&lt;Foo&gt;();
  Class&lt;Foo&gt; foo = instance.getGenericClass();
  </code></pre>
  
  <p>The lines of code from above are just to show you the (simplified) scenario I'm facing. If I would instantiate it by hand, then I would already know that I'm using <code>Foo</code> as generic parameter, but thats not the case. </p>
  
  <p>FYI I'm trying to deal with Android <code>Parcelable</code> and to get the correct class loader for <code>readParcelable()</code> by using generics. Concrete: <code>MyClass implements Parcelable</code>. While reading the <code>Parcel</code> I have to specify a classloader like this <code>data = parcel.readArrayList(Foo.class.getClassLoader)</code> and I want to determine that dynamically by using reflections like <code>data = parcel.readArrayList(getGenericClass().getClassLoader())</code></p>
  
  <p>Is there a way to get that kind of information?</p>
  
  <p>Typically you would just use:</p>
  
  <pre><code>Class type = (Class) (getClass().getGenericSuperclass()).getActualTypeArguments()[0]);
  </code></pre>
  
  <p>but that returns <code>java.util.List&lt;D&gt;</code>, but I'm interested in what <code>&lt;D&gt;</code> is. Is there a way to dive into that generic type as well? </p>