title: Java casting ".class"-operator used on a generic type, e.g. List, to "Class<List<?>>" and to "Class<List<Integer>>"
body: <p>I use the <code>.class</code>-operator to supply information about the contained type to a generic class.  For non-generic contained types, e.g. <code>Integer.class</code>, this works without any problems.  But with the contained type being a generic, e.g. <code>List&lt;Integer&gt;.class</code> or <code>List.class</code> it results in compile time errors about class casting.</p>
  
  <p>There is a way to circumvent the errors, but I'm curious about what is happening here.  Can someone explain what is happening?, why things are as they are?, and what the best way to circumvent the problem is?</p>
  
  <p>The following lines demonstrate the problem:
  Note the outer generic type expects <code>Class&lt;T&gt;</code> as parameter, so in this case <code>Class&lt;List&lt;Integer&gt;&gt;</code>.</p>
  
  <pre><code>Class&lt;Integer&gt; tInt = Integer.class;                     // Works as expected.
  Class&lt;List&gt; tList = List.class;              // Works with warning, but is not
                                               // what i'm looking for.
  Class&lt;List&lt;Integer&gt;&gt; tListInt1 = List.class;                          // Error
  Class&lt;List&lt;Integer&gt;&gt; tListInt2 = (Class&lt;List&lt;Integer&gt;&gt;) List.class;   // Error
  Class&lt;List&lt;?&gt;&gt; tListGeneric = (Class&lt;List&lt;Integer&gt;&gt;) List.class;      // Error
  </code></pre>
  
  <p>The next line works:</p>
  
  <pre><code>Class&lt;List&lt;Integer&gt;&gt; tListInt3 = 
                  (Class&lt;List&lt;Integer&gt;&gt;) ((Class&lt;Integer&gt;)List.class);
  </code></pre>
  
  <p>Why do the declarations of <code>tListInt2</code> and <code>tListGeneric</code> give and error?
  Why does upcast and then downcast with <code>tListInt3</code> not produce an error?
  Is there a better way to declare <code>tListInt3</code>?</p>
  
  <p>With kind regards,<br/>
  Kasper van den Berg</p>
  
  <p>ps. Let me know if you like to see code the outer generic container that needs this type information; i'll post it if needed.</p>