今天看一个开源库源码的时候,发现里面针对泛型Type
做了很多处理,我这块不怎么了解,故此研究一下。
关于java.lang.reflect.Type
的分类先说明一下,Type
作为一个接口,下面有4个继承它的子接口,分别是TypeVariable
,ParameterizedType
,WildcardType
,GenericArrayType
。这里我就不给专业名词了,之前我看很多文章,给的专业名词,到最后我也没能区分清楚,这里就直接上例子,通过例子来说明。
TypeVariable
这个怎么说,看字面翻译的意思是类型变量,我个人理解呢,它其实相当于在方法声明当中的形参。也就是你声明时写的是啥,获取到的就是啥。
public class GenericType { public static void main(String[] args) { ChildCls childCls = new ChildCls(); } } class SuperCls<K, V> { public SuperCls() { TypeVariable<?>[] typeParameters = getClass().getSuperclass().getTypeParameters();// [K,V] for (TypeVariable<?> typeVariable : typeParameters) { p("getSuperclass().getTypeParameters()=" + typeVariable);// 这里分别输出K,V Type[] bounds = typeVariable.getBounds(); for (Type type : bounds) { p(type);// 分别输出class java.lang.Object } } } void p(Object obj) { System.out.println(obj.toString()); } } class ChildCls extends SuperCls<SuperCls<? extends String, ? super String>, Integer> {}
ParameterizedType
这个,字面意思,参数化的类型。个人理解相当于你调用方法(声明的泛型类),并传入一些参数(泛型类型)。还是上面的例子。
class SuperCls<K, V> { public SuperCls() { Type genericSuperclass = getClass().getGenericSuperclass(); p("getGenericSuperclass()=" + genericSupe