How does Java resolve generic type parameters that aren't in method declaration?
<p>While trying to solve a problem, I ended up writing a method with a type parameter that isn't mentioned in the arguments nor in the return type, namely a <code>&lt;T&gt; void authenticate(Credentials credentials)</code> method. The only dependency on <code>T</code> is in the method body (details ahead). So my question is: <strong>how is that generic type resolved</strong>? I couldn't find any other example code with that kind of generic type parameter.</p>

<p>So the body of that method is something like</p>

<pre><code>public &lt;T extends AuthResponse&gt; void authenticate(Credentials credentials) {
    Call&lt;T&gt; call = getAuthCall(credentials);
    Response&lt;T&gt; response = call.execute();

    // doSomething is an AuthResponse method
    response.body().doSomething();
}
</code></pre>

<p>which calls a method with only a generic return type, which goes like this:</p>

<pre><code>private Call&lt;T extends AuthResponse&gt; getAuthCall(Credentials credentials) {
    if (credentials instanceof CredentialsA)
        return (Call&lt;T&gt;) service.authenticate((CredentialsA) credentials);
    else if (credentials instanceof CredentialsB)
        return (Call&lt;T&gt;) service.authenticate((CredentialsB) credentials);
    else
        throw new IllegalArgumentException();
}
</code></pre>

<p>So the type parameters of the two methods seem to be related. But I couldn't understand how. Also the <code>(Call&lt;T&gt;)</code> cast doesn't seem like a nice solution to my problem — <code>service</code> is a Retrofit interface like this:</p>

<pre><code>public interface AuthServiceInterface {
    @POST("auth/a") Call&lt;AuthResponseA&gt; authenticate(CredentialsA credentials);
    @POST("auth/b") Call&lt;AuthResponseB&gt; authenticate(CredentialsB credentials);
}
</code></pre>