Java Reference
In-Depth Information
Finally, note that a static method such as
merge
can be a generic meth-
od, though it cannot refer to any type variables of its own generic class.
11.3.1. Generic Invocations and Type Inference
If you invoke a generic method like
toArray
or
merge
, the compiler must
ensure, as it does for all method invocations, that you pass in argu-
ments of the right type and assign any return value to a variable of the
right type. When you create an instance of a generic class, you use a
parameterized type to bind a particular type argument to the type vari-
ables of the class. Similarly, you can parameterize a method invocation
to supply type arguments for the method's type variables. For example,
consider this generic method that simply returns its argument:
<T> T passThrough(T obj) {
return obj;
}
You can invoke
passThrough
as a
String
method:
String s1 = "Hello";
String s2 = this.<String>passThrough(s1);
This parameterized method invocation tells the compiler that
T
should be
treated as
String
and that the arguments and return value of
passThrough
must be verified accordingly.
Fortunately, explicitly parameterizing a method invocation is rarely
needed. In the absence of a type argument, the compiler will infer what
type to use from the static argument types and the way in which the
return type is used. For example, this invocation of
passThrough
is equi-
valent to the previous one but relies on type inference to establish the
type of
T
: