Java Reference
In-Depth Information
// Specify that Integer is the actual type for the type parameter for m1()
t.<Integer>m1(iw1, iw2, "hello");
// Let the compiler figure out the actual type parameter for the m1() call
// using types for iw1 and iw2
t.m1(iw1, iw2, "hello"); // OK
Listing 4-3 demonstrated how to declare a generic static method. You cannot refer to the type parameters of the
containing class inside the static method. A static method can refer only to its own declared type parameters. Below
is the copy of your copy() stati c method from the WrapperUtil class. It defines a type parameter T , which is used to
constrain the type of arguments source and dest .
public static <T> void copy(Wrapper<T> source, Wrapper<? super T> dest) {
T value = source.get();
dest.set(value);
}
The compiler will figure out the actual type parameter for a method whether the method is non-static or static.
However, if you want to specify the actual type parameter for a static method call, you can do so as follows:
WrapperUtil. <Integer> copy(iw1, iw2);
You can also define type parameters for constructors the same way as you do for a method. The following code
defines a type parameter U for the constructor of class Test . It places a constraint that the constructor's type parameter
U must be the same or a subtype of the actual type of its class type parameter T .
public class Test<T> {
public <U extends T> Test(U k) {
// Do something
}
}
The compiler will figure out the actual type parameter passed to the constructor with the value you pass. If you
want to specify the actual type parameter value for the constructor, you can specify it in angle brackets between the
new operator and the name of the constructor, as shown in the following snippet of code:
// Specify the actual type parameter for the constructor as Double
Test<Number> t1 = new <Double> Test<Number>(new Double(12.89));
// Let the compiler figure out that we are using Integer as
// the actual type parameter for the constructor
Test<Number> t2 = new Test<Number>(new Integer(123));
Type Inference in Generic Object Creation
Java 7 added limited support for type inference in an object-creation expression for generic types. Note that the type
inference support in the object-creation expression is limited to the situations where the type is obvious. Consider the
following statement:
List<String> list = new ArrayList<String>();
 
Search WWH ::




Custom Search