Java Reference
In-Depth Information
Lower-Bounded Wildcards
Specifying a lower-bound wildcard is the opposite of specifying an upper-bound wildcard. The syntax for using a
lower-bound wildcard is
<? super T>
, which means “anything that is a supertype of
T
.” Let's add another method to
the
WrapperUtil
class. You will call the new method
copy()
and it will copy the value from a source wrapper object to
a destination wrapper object. Here is the first attempt. The
<T>
is the formal type parameter for the
copy()
method. It
specifies that the
source
and
dest
parameters must be of the same type.
public class WrapperUtil {
public static <T> void copy(Wrapper<T> source, Wrapper<T> dest) {
T value = source.get();
dest.set(value);
}
}
Copying the content of a
Wrapper<String>
to a
Wrapper<Object>
using your
copy()
method will not work.
Wrapper<Object> objectWrapper = new Wrapper<Object>(new Object());
Wrapper<String> stringWrapper = new Wrapper<String>("Hello");
WrapperUtil.copy(stringWrapper, objectWrapper); // A compile-time error
The above code will generate a compile-time error because the
copy()
method requires the
source
and the
dest
arguments be of the same type. However, for all practical purposes a
String
is always an
Object
. Here, you need to
use a lower-bounded wildcard, as shown:
public class WrapperUtil {
// New definition of the copy() method
public static <T> void copy(Wrapper<T> source, Wrapper<? super T> dest){
T value = source.get();
dest.set(value);
}
}
Now you are saying that the
dest
argument of the
copy()
method could be either
T
, same as
source
, or any of its
supertype. You can use the
copy()
method to copy the contents of a
Wrapper<String>
to a
Wrapper<Object>
as shown
below. Since
Object
is the supertype of
String,
the new
copy()
method will work. However, you cannot use it to copy
from an
Object
type wrapper to a
String
type wrapper, as an
Object
is a
String
is not always true.
Wrapper<Object> objectWrapper = new Wrapper<Object>(new Object());
Wrapper<String> stringWrapper = new Wrapper<String>("Hello");
WrapperUtil.copy(stringWrapper, objectWrapper); // OK with the new copy() method
Listing 4-3 shows the complete code for the
WrapperUtil
class.
Listing 4-3.
A WrapperUtil Utility Class That Works with Wrapper Objects
// WrapperUtil.java
package com.jdojo.generics;
public class WrapperUtil {
public static void printDetails(Wrapper<?> gw) {
// Can assign get() return value to Object