反射Type

出自本人的个人博客.
被人盗用

概览

Type是个顶层接口类,它有几个子类和子接口。

Type WildcardType ParameterizedType TypeVariable GenericArrayType Class<?>
getTypeName() : String getLowerBounds() : Type[] getActualTypeArguments() : Type[] getBounds() : Type[] getGenericComponentType() :Type isPrimitive() : boolean,isArray(),isInterface(), isInstance(Object), isAnnotation(), isSynthetic(),
getUpperBounds() : Type[] getRawType() : Type getGenericDeclaration() : D
getOwnerType() : Type getName() : String getTypeParameters(): TypeVariable>[]
getAnnotatedBounds() : AnnotatedType[]

TypeVariable<D extends GenericType>

TypeVariable表示的是泛型类型T

GenericDeclaration表明泛型声明在哪里。泛型的声明一般在以下几个地方:

在类上声明泛型T

class  Student<T>  {
}
//获取类上声明的泛型类型T
TypeVariable<Class<Student>>[] typeParameters =  Student.class.getTypeParameters();

方法上声明泛型T`

public  <T extends  Student> T get(){
   return  null;`
  }

Method method = clazz.getMethod("get");
Type type = method.getGenericReturnType();
//因为方法get的返回类型是泛型类型T,所以type的实际类型是TypeVariable,又因为这个泛型类型T是在方法上声明的
TypeVariable<Method> typeVariable =  (TypeVariable<Method>)type;

构造函数声明泛型

public  <T>  Student(T t){
}

//获取泛型类型T
//因为构造函数的参数类型是泛型类型T,所以这里传入Object
Constructor<Student> constructor =  Student.class.getConstructor(Object.class);
//返回构造函数上声明的泛型类型T的数组
TypeVariable<Constructor<Student>>[] typeParameters = constructor.getTypeParameters();

ConstructorMethodExecutable继承了方法getTypeParameters()

  1. //返回方法上声明的泛型类型T的数组。
  2. TypeVariable<Method>[] typeParameters = method.getTypeParameters();

WildcardType

泛型通配符?,<? extends Number>等。

ParameterizedType

​官方解释ParameterizedType represents a parameterized type such as Collection<String>

不明白为什么用的是Parameterized这个单词。字面意思理解为参数化的类型。很难懂到底是啥。自己的话来说就是这个类型所使用的类一定要带有泛型。

比如方法返回值类型。

public  List<String> get(){
 return  null;
}

get方法返回值为List<String>List带了泛型。也就是类型所使用的的任何类只要带了泛型,它的类型都是ParameterizedType

GenericArrayType

字面意思就能看出这个类型表示的是个数组。数组元素是什么类型呢?官方文档做了说明。

{@code GenericArrayType} represents an array type whose component type is either a parameterized type or a type variable.

数组元素类型有两种:

  1. 数组元素类型是ParameterizedType
    比如:List<String>[],数组元素类型是List<String>
  2. 数组元素类型是泛型类型T,也就是TypeVariable类型。
    比如:T[]。数组元素类型是泛型类型T。

对于数组元素类型为具体类型的比如基本变量类型int[],明确的对象类型Student[]System[](自定义的对象类Student,系统的类System),这些元素类型既不是ParameterizedType,又不是TypeVariable,因此它的类型是Class<?>

Class<?>[]

基本变量,对象(自定义的类和接口,枚举类),字符串String,以及以这些类型作为元素类型的数组。都是Class<?>

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理