The Java Language Specification for Java 8 provides an example of a method call with a type argument in "Example 4.11-1. Usage of a Type":
<S> void loop(S s) {
this.<S>loop(s); // <S> is the the type argument for the method call.
}
In that example the supplied type argument is meaningful, but apparently type arguments for method calls can also be redundant and completely meaningless, and generics need not even be involved. For example:
void m() { }
void test() {
m();
this.m();
this.<Integer>m(); // Compiles and runs OK!
this.<String, Byte, StringBuilder, Thread[], Throwable>m(); // Compiles and runs OK!
<Integer>m(); // Won't compile: "illegal start of expression"
}
I have a couple of questions arising:
Can anyone suggest a valid reason for Java allowing these redundant type parameters? Accepting that they do no harm, it still seems to me like something that the compiler could and should catch.
That code only compiles if the method calls with type arguments are prefixed with "this.". Otherwise you get "illegal start of expression" errors. Is that a bug? Shouldn't any unambiguous method call that works with "this." also work without "this."?
(The catalyst for these questions is Oracle's response to a bug report I created for an interesting Java problem someone raised here on SO.)
UPDATE Sep 18, 2015
- I raised bug JDK-8098556 for this issue with Oracle. Here is their response:
This is not an issue; method references are checked using same rules as plain methods - note that for ordinary methods you can always supply redundant type-arguments:
void m() { }
this.<String>m(); //legal
Method (and constructor) references simply inherit this behavior, as per 15.13: ""If the method reference expression has the form ReferenceType :: [TypeArguments] Identifier, the potentially applicable methods are the member methods of the type to search that have an appropriate name (given by Identifier), accessibility, arity (n or n-1), and type argument arity (derived from [TypeArguments]), as specified in §15.12.2.1."
- Since that response confirms the information TAsk had already provided below (including citing the relevant section of JLS), I have accepted that answer.