目录
一、 泛型与继承
代码:
报错。
二、 泛型擦除
三、 多边界擦除
四、 泛型与反射
1. TypeVariable
2. WildcardType
3. ParameterizedType
4. GnericArrayType
代码:
结果:
五、 泛型的限制与问题
一、 泛型与继承
继承后的泛型类会被擦除成边界。
代码:
package fanXin2;
public class GenericTest {
public static void main(String[] args) {
Zoo zoo = new Zoo(new Animal());
Zoo birdzoo = new Zoo(new Bird());
//zoo = birdzoo; // 不合法
}
}
报错。
二、 泛型擦除
泛型擦除:泛型代码在编译后,都会被擦除成原生类型(边界)。
三、 多边界擦除
四、 泛型与反射
1. TypeVariable
描述类型参数。
2. WildcardType
描述通配符表达式。如: ? extends Number
3. ParameterizedType
描述参数化的类。如: List
4. GnericArrayType
描述泛型数组。
代码:
public class Zoo {
}
package fanXin2;
import java.lang.reflect.TypeVariable;
import java.util.Arrays;
public class GenericTest {
public static void main(String[] args) throws Exception{
Zoo fishZoo = new Zoo();
Zoo birdZoo = new Zoo();
Person person = new Person();
TypeVariable[] fishTypes = fishZoo.getClass().getTypeParameters(); //获取参数类型
TypeVariable[] birdTypes = birdZoo.getClass().getTypeParameters();
TypeVariable[] personTypes = person.getClass().getTypeParameters();
System.out.println("fishZoo的参数类型:" + Arrays.toString(fishTypes));
System.out.println("birdZoo的参数类型:" + Arrays.toString(birdTypes));
System.out.println("personZoo的参数类型:" + Arrays.toString(personTypes));
}
}
结果:
fishZoo的参数类型:[T]
birdZoo的参数类型:[T]
personZoo的参数类型:[]
fishZoo的参数类型:[T] birdZoo的参数类型:[T] personZoo的参数类型:[]
五、 泛型的限制与问题



