随笔博文

Java中与泛型相关的接口 之 TypeVariable

2022-12-06 12:55:04 michael007js 175

简介

TypeVariable是“类型变量”(或者叫“泛型变量”更准确些)的通用的顶级接口。在泛型编程中会用到“泛型变量”来描述类型,或者说是用来表示泛型。一般用大写字母作为类型变量,比如K、V、E等。

说到TypeVariable<D extends GenericDeclaration>就不得不提起java泛型中另一个比较重要的接口对象,GenericDeclaration接口对象。该接口用来定义哪些对象上是可以声明(定义)“范型变量”,所谓“范型变量”就是<E extends List>或者<E>, 也就是TypeVariable<D extends GenericDeclaration>这个接口的对应的对象,TypeVariable<D extends GenericDeclaration>中的D是extends GenericDeclaration的,用来通过“范型变量”反向获取拥有这个变量的GenericDeclaration。

【注意】类型变量声明(定义)的时候不能有下限(既不能有super),否则编译报错。为什么?T extends classA表示泛型有上限classA,当然可以,因为这样,每一个传进来的类型必定是classA(具有classA的一切属性和方法),但若是T super classA,传进来的类型不一定具有classA的属性和方法,当然就不适用于泛型。

Type[] getBounds()

获得该“范型变量”的上限(上边界),若无显式定义(extends),默认为Object。类型变量的上限可能不止一个,因为可以用&符号限定多个(这其中有且只能有一个为类或抽象类,且必须放在extends后的第一个,即若有多个上边界,则第一个&后必为接口)。

下面是一个例子:

package com.ibestcode.wfso.web.blog.Controller;import java.util.Map;import java.lang.reflect.*;public class Test<K extends Integer & Map, V>{
K key;
V value;
public static void main(String[] args) throws Exception{
Type[] types = Test.class.getTypeParameters();
for(Type type : types){
TypeVariable t = (TypeVariable)type;
System.out.println(t.getGenericDeclaration());
int size = t.getBounds().length;
System.out.println(t.getBounds()[size - 1]);
System.out.println(t.getName() + "\n-------------分割线-------------");
}
}}// 下面是运行结果class com.ibestcode.wfso.web.blog.Controller.Testinterface java.util.Map
K-------------分割线-------------class com.ibestcode.wfso.web.blog.Controller.Testclass java.lang.Object
V-------------分割线-------------Process finished with exit code 0

D getGenericDeclaration()

获得声明(定义)这个“范型变量”的类型及名称,即如:

//当声明这个“范型变量”的GenericDeclaration是一个类时class com.xxx.xxx.classA

//当声明这个“范型变量”的GenericDeclaration是一个方法时public void com.fcc.test.Main.test(java.util.List) //当声明这个“范型变量”的GenericDeclaration是一个构造器时public com.fcc.test.Main()

String getName()

获得这个“范型变量”在声明(定义)时候的名称。如:K、V、E等。

AnnotatedType[] getAnnotatedBounds()

还不知道什么用,肯定和注解相关。


首页
关于博主
我的博客
搜索