How to cast Java generic types
Description
You can cast one instance of a generic class into another only if the two are compatible and their type arguments are the same.
Example
For example, assuming the following program, this cast is legal:
class Gen<T> {
T ob;/*from w ww. j a va 2 s. c o m*/
Gen(T o) {
ob = o;
}
T getob() {
return ob;
}
}
class Gen2<T> extends Gen<T> {
Gen2(T o) {
super(o);
}
}
public class Main {
public static void main(String args[]) {
Gen<Integer> iOb = new Gen<Integer>(88);
Gen2<Integer> iOb2 = new Gen2<Integer>(99);
Gen2<String> strOb2 = new Gen2<String>("Generics Test");
iOb = (Gen<Integer>) iOb2;
}
}
because iOb2 is an instance of Gen<Integer>. But, this cast:
class Gen<T> {
T ob;// w ww . j a v a 2 s . com
Gen(T o) {
ob = o;
}
T getob() {
return ob;
}
}
class Gen2<T> extends Gen<T> {
Gen2(T o) {
super(o);
}
}
public class Main {
public static void main(String args[]) {
Gen<Integer> iOb = new Gen<Integer>(88);
Gen2<Integer> iOb2 = new Gen2<Integer>(99);
Gen2<String> strOb2 = new Gen2<String>("Generics Test");
//iOb = (Gen<Long>) iOb2;//wrong
}
}
is not legal because iOb2 is not an instance of Gen<Long>.