Note that there are some explanatory texts on larger screens.

plurals
  1. POWhy should I care that Java doesn't have reified generics?
    primarykey
    data
    text
    <p>This came up as a question I asked in an interview recently as something the candidate wished to see added to the Java language. It's commonly-identified as a pain that Java doesn't have <a href="http://gafter.blogspot.com/2006/11/reified-generics-for-java.html" rel="noreferrer">reified generics</a> but, when pushed, the candidate couldn't actually tell me the sort of things that he could have achieved were they there.</p> <p>Obviously because raw types are allowable in Java (and unsafe checks), it is possible to subvert generics and end up with a <code>List&lt;Integer&gt;</code> that (for example) actually contains <code>String</code>s. This clearly could be rendered impossible were type information reified; <em>but there must be more than this</em>!</p> <p>Could people post examples of things that <strong>they would really want to do</strong>, were reified generics available? I mean, obviously you could get the type of a <code>List</code> at runtime - but what would you do with it?</p> <pre><code>public &lt;T&gt; void foo(List&lt;T&gt; l) { if (l.getGenericType() == Integer.class) { //yeah baby! err, what now? </code></pre> <p><strong>EDIT</strong>: A quick update to this as the answers seem mainly to be concerned about the need to pass in a <code>Class</code> as a parameter (for example <code>EnumSet.noneOf(TimeUnit.class)</code>). I was looking more for something along the lines of <em>where this just isn't possible</em>. For example:</p> <pre><code>List&lt;?&gt; l1 = api.gimmeAList(); List&lt;?&gt; l2 = api.gimmeAnotherList(); if (l1.getGenericType().isAssignableFrom(l2.getGenericType())) { l1.addAll(l2); //why on earth would I be doing this anyway? </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
 

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