Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>The reason the constructor works is that you're explicitly specifying the type parameters. The static method also will work if you do that:</p> <pre><code>Pair&lt;Class&lt;?&gt;, String&gt; pair = Pair.&lt;Class&lt;?&gt;, String&gt;of(List.class, "hello"); </code></pre> <p>Of course, the whole reason you have a static method in the first place is probably just to get the type inference (which doesn't work with constructors at all).</p> <p>The problem here (as you suggested) is that the compiler is performing <a href="http://docs.oracle.com/javase/specs/jls/se7/html/jls-5.html#jls-5.1.10" rel="noreferrer">capture conversion</a>. I believe this is as a result of<a href="http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.12.2.6" rel="noreferrer"> [§15.12.2.6 of the JLS]</a>:</p> <blockquote> <ul> <li>The result type of the chosen method is determined as follows: <ul> <li>If the method being invoked is declared with a return type of void, then the result is void.</li> <li>Otherwise, if unchecked conversion was necessary for the method to be applicable then the result type is the erasure (§4.6) of the method's declared return type.</li> <li>Otherwise, if the method being invoked is generic, then for 1in, let Fi be the formal type parameters of the method, let Ai be the actual type arguments inferred for the method invocation, and let R be the declared return type of the method being invoked. The result type is obtained by applying capture conversion (§5.1.10) to R[F1 := A1, ..., Fn := An].</li> <li>Otherwise, the result type is obtained by applying capture conversion (§5.1.10) to the type given in the method declaration.</li> </ul></li> </ul> </blockquote> <p>If you really want the inference, one possible workaround is to do something like this:</p> <pre><code>Pair&lt;? extends Class&lt;?&gt;, String&gt; pair = Pair.of(List.class, "hello"); </code></pre> <p>The variable <code>pair</code> will have a wider type, and it does mean a bit more typing in the variable's type name, but at least you don't need to cast in the method call anymore.</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