Java Reference
In-Depth Information
The static argument type of
Object
requires that
T
, as the return type of
the method, be
Object
(or a supertype if
Object
had one) and the
String
type of
s1
requires that
T
be assignable to
String
. But there is no such
typeyou cannot assign an
Object
to a
String
reference. Of course, you
can inform the compiler that you know the returned object actually is a
String
by inserting an additional cast:
s1 = (String) passThrough((Object) s1);
The actual type inference process and the rules controlling it are ex-
tremely complex, but for the most part you don't need to care what
the actual inferred type is as long as the code compiles. For example,
if a generic method took two parameters of type
T
and you invoked it
passing a
List<String>
and a
List<Number>
, then the inferred type could
be
List<?>
. Inference is also used as part of determining which method
to invoke, as you will see shortly.
The inference process may result in simple types like
Object
or
String
,
or more complex types for which no single class or interface declaration
existssuch as a type that is both
Runnable
and
Cloneable
. These complex
types are generally known as
intersection types.
For each constraint on
a type variable there will be a set of types that meet that constraint. The
intersection of those sets contains the inferred type.
Finally, note that if you do wish to make a parameterized method in-
vocation, you cannot parameterize an invocation that uses just a simple
method name:
String s1 = "Hello";
String s2 = <String>passThrough(s1); // INVALID: won't
compile
Instead you must qualify the method name appropriately, such as by
using
this
or
super
for instance methods, or the class name for static
methods.