快捷搜索: 王者荣耀 脱发

getType() 和 getGenericType()的区别

处理泛型时会经常用到这两个方法,但是二者的区别是什么?

先看看官方的解释:

getType ==》:Returns a Class object that identifies the declared type for the field represented by this Field object.

返回字段对象声明类型的类对象。

getGenericType =》Returns a Type object that represents the declared type for the field represented by this Field object. If the Type is a parameterized type, the Type object returned must accurately reflect the actual type parameters used in the source code. If the type of the underlying field is a type variable or a parameterized type, it is created. Otherwise, it is resolved.

返回字段对象声明类型的type对象, Type是参数化类型,则在源代码中必须准确返回Type对象的实际类型参数。

不是我外语不好,实在是官方的解释太几把烂了,写的啥玩意儿!

千言万语BB不如一句话代码,用代码来证明吧:

从上面的例子可以看到:

如果字段类型是泛型:

getType()只会返回泛型尖括号前面的类型,也就是集合的类型

getGenericType()会同时返回集合类型和尖括号里面的泛型类型。

这就是差别!

还有一个重点需要注意:泛型其实有一个隐含的前提:泛型的载体一定是集合!(List ,Map,Set之类的),原因很简单!因为正是对成员变量进行类型约束,才产生了泛型,那么它作用的对象一定是一组成员,那不就正好是集合类型了

如果字段类型不是泛型:getType() 和 getGenericType()返回值则是一样的

经验分享 程序员 微信小程序 职场和发展