目录
一、 泛型与继承
继承后的泛型类会被擦除成边界。
代码:
package fanXin2;
/**
* @author: y9
* @Date: 2021/10/04
*/
public class GenericTest {
public static void main(String[] args) {
Zoo<Animal> zoo = new Zoo<Animal>(new Animal());
Zoo<Bird> birdzoo = new Zoo<Bird>(new Bird());
//zoo = birdzoo; // 不合法
}
}
报错。
二、 泛型擦除
泛型擦除:泛型代码在编译后,都会被擦除成原生类型(边界)。
三、 多边界擦除
四、 泛型与反射
1. TypeVariable
描述类型参数。
2. WildcardType
描述通配符表达式。如: ? extends Number
3. ParameterizedType
描述参数化的类。如: List<String>
4. GnericArrayType
描述泛型数组。
代码:
public class Zoo<T> {
}
package fanXin2;
import java.lang.reflect.TypeVariable;
import java.util.Arrays;
/**
* @author: y9
* @Date: 2021/10/04
*/
public class GenericTest {
public static void main(String[] args) throws Exception{
Zoo<Fish> fishZoo = new Zoo<Fish>();
Zoo<Bird> birdZoo = new Zoo<Bird>();
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的参数类型:[]
五、 泛型的限制与问题