title: Java not choosing the most specific method when called through a generic wrapper?
body: <p>According to this <a href="https://docs.oracle.com/javase/specs/jls/se18/html/jls-15.html#jls-15.12.2.5" rel="nofollow noreferrer">https://docs.oracle.com/javase/specs/jls/se18/html/jls-15.html#jls-15.12.2.5</a>, the Java compiler will attempt to choose the most specific method to invoke when multiple applicable and accessible ones are available. The intuition is that more specific method can be substituted by less specific ones but not vice versa.</p>
  <p>So I'm a bit surprised that this won't work when we wrap the ambiguous call within a generic wrapper as follows:</p>
  <pre><code>public class Test{
          static &lt;T&gt; void direct(T t) { System.out.println(&quot;generic&quot;);}
          static void direct(int t) { System.out.println(&quot;specific-int&quot;);}
  
          static &lt;T&gt; void indirect(T t) { direct(t);}
          
          public static void main ( String [] args ) {
              direct(1);    // print specific-int
              indirect(1);  // print generic
          }
       }
  </code></pre>
  <p>So we can see that just calling <code>direct</code> makes it works as expected. But when calling <code>indirect</code>, the less specific method is called instead.</p>
  <p>The behavior changes if I change the type of the direct method as such</p>
  <pre><code>    static void direct(short t) { System.out.println(&quot;specific-short&quot;);}
  </code></pre>
  <p>In this case both lines print <code>generic</code> instead (the <code>short</code> method isn't called in either case), which tells me that the literal <code>1</code> was implicitly casted to <code>int</code> in the first instance. If that's the case, why wasn't it called with the more specific method that takes in <code>int</code> as an argument?</p>