title: How to Cast the Class Object of a Generic Type to a Specific Instance of that Type
body: <p>I have a generic interface, lets call it <code>GenericInterface&lt;T&gt;</code>. I need to pass the <em>class object</em> of that interface to a method that expects (specified through another type parameter) a specific instance of that type. Let's assume I want to call <code>java.util.Collections.checkedList()</code>:</p>
  
  <pre><code>List&lt;GenericInterface&lt;Integer&gt;&gt; list = Collections.checkedList(
      new ArrayList&lt;GenericInterface&lt;Integer&gt;&gt;(),
      GenericInterface.class);
  </code></pre>
  
  <p>This does not work because <code>Class&lt;GenericInterface&gt;</code> cannot be implicitly casted to <code>Class&lt;GenericInterface&lt;Integer&gt;&gt;</code>, what is the most type safe way to do that? The best I could come up is this:</p>
  
  <pre><code>List&lt;GenericInterface&lt;Integer&gt;&gt; list = Collections.checkedList(
      new ArrayList&lt;GenericInterface&lt;Integer&gt;&gt;(),
      (Class&lt;GenericInterface&lt;Integer&gt;&gt;) (Class&lt;?&gt;) GenericInterface.class);
  </code></pre>
  
  <p>It works but won't protect me from e.g. changing the list's type to <code>List&lt;SomeOtherInterface&gt;</code> without also replacing the class object parameter with <code>SomeOtherInterface.class</code>.</p>