Java重要技术(24)泛型之使用反射访问参数化类型

时间:2021-01-25 19:26:17

 

1.1. 用反射访问参数化类型

 

使用反射机制可以获取到一部分参数化类型有关的信息。

public class GenericParameterTest5 {



static class Base{}

static class Generic<T extends Base>{



public T work( List<T> list){

return list.get(0);

}



public T work( T obj){

return obj;

}

}



public static void main(String[] args) {





try {





//public T work( List<T> list){

Method method1
= Generic.class.getMethod("work", List.class);

System.out.println(method1.getParameters()[
0].getType());



Type t1
= method1.getGenericParameterTypes()[0];

ParameterizedType pt
= (ParameterizedType)t1;

System.out.println(
"rawtype:" +pt.getRawType()

+ "actualtype:" + pt.getActualTypeArguments()[0].getTypeName());



System.out.println(
"-------------");



//public T work( T obj){

Method method2
= Generic.class.getMethod("work", Base.class);

System.out.println(method2.getParameters()[
0].getType());



Type t2
= method2.getGenericParameterTypes()[0];

TypeVariable
<?> tv = (TypeVariable)t2;

System.out.println(tv.getTypeName());

GenericDeclaration gd
= tv.getGenericDeclaration();

System.out.println(gd.getTypeParameters()[
0]);



}
catch (NoSuchMethodException | SecurityException e) {

e.printStackTrace();

}

}

}

 

 

运行结果如下:

interface java.util.List

rawtype:interface java.util.Listactualtype:T

-------------

class com.test.javatechnology.genericparameter.GenericParameterTest5$Base

T

T