Java Reference
In-Depth Information
Object value = gw.get();
String className = null;
if (value != null) {
className = value.getClass().getName();
}
System.out.println("Class: " + className);
System.out.println("Value: " + value);
}
public static double sum(Wrapper<? extends Number> n1,
Wrapper<? extends Number> n2) {
Number num1 = n1.get();
Number num2 = n2.get();
double sum = num1.doubleValue() + num2.doubleValue();
return sum;
}
public static <T> void copy(Wrapper<T> source, Wrapper<? super T> dest) {
T value = source.get();
dest.set(value);
}
}
Generic Methods and Constructors
You can define type parameters in a method declaration. They are specified in angle brackets before the return type
of the method. The type that contains the generic method declaration does not have to be a generic type. You can
use the type parameter specified for the generic type inside the non-static method declaration. In your Wrapper class,
you have used the type parameter T in the get() and set() methods. You can also define new type parameters for
methods. The snippet of code shown below defines a new type parameter V for method m1() . The new type parameter
V forces the first and the second arguments of method m1() to be of the same type. The third argument must be of the
same type T , which is the type of the class instantiation.
public class Test<T> {
public <V> void m1(Wrapper<V> a, Wrapper<V> b, T c) {
// Do something
}
}
How do you specify the generic type for a method when you want to call the method? Usually, you do not need to
specify the actual type parameter when you call the method. The compiler figures it out for you using the value you pass
to the method. However, if you ever need to pass the actual type parameter for the method's formal type parameter, you
must specify it in angle brackets ( < > ) between the dot and the method name in the method call, as shown:
Test<String> t = new Test<String>();
Wrapper<Integer> iw1 = new Wrapper<Integer>(new Integer(201));
Wrapper<Integer> iw2 = new Wrapper<Integer>(new Integer(202));
 
Search WWH ::




Custom Search