Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>we have two generic types here, one for subtype of collection, one for element type of collection. following code can work:</p> <pre><code>private static &lt;C extends Collection&lt;E&gt;, E&gt; C create(Class&lt;C&gt; cls) throws Exception { return cls.newInstance(); } </code></pre> <p>usage example. no warnings.</p> <pre><code> Class&lt;LinkedList&lt;String&gt;&gt; clazz = ...; LinkedList&lt;String&gt; result = create(clazz); </code></pre> <p>the question now becomes how do we obtain <code>clazz</code>? You have to convince the compiler really hard:</p> <pre><code> List&lt;String&gt; list = new LinkedList&lt;String&gt;(); clazz = (Class&lt;LinkedList&lt;String&gt;&gt;)list.getClass(); clazz = (Class&lt;LinkedList&lt;String&gt;&gt;)(Class&lt;?&gt;)LinkedList.class; </code></pre> <p>we can have a utility method to ease the type casting:</p> <pre><code>public static &lt;C extends Collection, E, T extends Collection&lt;E&gt;&gt; Class&lt;T&gt; type(Class&lt;C&gt; classC, Class&lt;E&gt; classE) { return (Class&lt;T&gt;)classC; } //usage: clazz = type(LinkedList.class, String.class); result = create(clazz); </code></pre> <p>The fun is recurive:</p> <pre><code> Class&lt;LinkedList&lt;LinkedList&lt;String&gt;&gt;&gt; clazz2; LinkedList&lt;LinkedList&lt;String&gt;&gt; result2; clazz2 = type(LinkedList.class, clazz); result2 = create(clazz2); </code></pre> <p>But at some point, we have to stop this silly game. Generic typing is supposed to help us, not to torture us. When it becomes too cumbersome and makes our programs impossible to read, just drop it. Use the god damn raw types that we have lived with happily for years.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload