~~java 反射类型Type学习~~
参考文档:JAVA15语言官方文档
一、Type介绍
Type是Java 编程语言中所有类型的公共高级接口,也就是Java中所有"类型"的接口。官方原话定义如下
官方文档:Type is the common superinterface for all types in the Java programming language. These include raw types, parameterized types, array types, type variables and primitive types.
这样的官方描述有点难懂,此处我画个图解释一下。Type其实是和泛型一起出现的,可以说Type就是为了支持泛型。
- 泛型出现之前,我们可以通过Class来确认一个对象的类型,比如ClassA A,那么A的类型就是ClassA;
- 泛型出现之后,显然不能通过Class唯一确认一个对象的类型,比如List<ClassA> A,A的Class是List,但是A的类型显然不仅仅是List,它是由Class类型的List + TypeVariables的ClassA联合确认的一个Type。
A type variable is an unqualified identifier used as a type in class, interface, method, and constructor bodies.
The types of the Java programming language are divided into two kinds: primitive types and reference types. The primitive types are the boolean type and the numeric types. The numeric types are the integral types byte, short, int, long, and char, and the floating-point types float and double. The reference types are class types, interface types, and array types. There is also a special null type. An object is a dynamically created instance of a class type or a dynamically created array. The values of a reference type are references to objects. All objects, including arrays, support the methods of class Object . String literals are represented by String objects.
二、Type的类型
Type可以分为两大类:包含TypeVariables和不包含TypeVariables的类型:
- 不包含TypeVariable:包含基本数据类型(int, long等),基本Class(如Object,不包含泛型的类);
- 包含TypeVariable,按照包含的TypeVariable又分为以下几类:
- ParameterizedType: 表示一种参数化的类型,如List<String>,泛型的参数已经指定;
- GenericArrayType: 表示一种元素类型是参数化类型或者类型变量的数组类型,如List<String>[][];
- WildcardType: 代表一种通配符类型表达式,比如List<?>, List<? extends ClassA>, List<? super Object>。
继续介绍Type之前,需要先介绍一下java的泛型机制:
泛型是Java SE 1.5的新特性,泛型的本质是参数化类型,也就是说所操作的数据类型被指定为一个参数。这种参数类型可以用在类、接口和方法的创建中,分别称为泛型类、泛型接口、泛型方法。 Java语言引入泛型的好处是安全简单。泛型的好处是在编译的时候检查类型安全,并且所有的强制转换都是自动和隐式的,以提高代码的重用率。
泛型信息只存在于代码编译阶段,