Java 中的泛型仅仅是给编译器 javac 使用的,确保数据的安全性和免去强制类型转换的麻烦,但是一旦编译完成,所有与泛型有关的类型全部擦除。
使用泛型直接读取泛型,是读取不到的,因为反射是操作加载以后的类的。
为了通过反射操作这些类型以迎合实际开发的需要
1) ParameterizedType : 表 示 一 种 参 数 化 的 类 型 , 比 如 Collection<String>,可以获取 String 信息
2) GenericArrayType:泛型数组类型
3) TypeVariable:各种类型变量的公共父接口
4) WildcardType:代表一种通配符类型表达式, 比如?extendsNumber,?superInteger (Wildcard 是一个单词,就是通配符)
例一:
1 public class Test4 { 2 public static void main(String[] args) throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { 3 List<String> alist=new ArrayList<String>(); 4 Class c=alist.getClass();//得到Class对象 5 Method m=c.getDeclaredMethod("add", Object.class); 6 //执行添加方法 7 m.invoke(alist, 123); 8 //输出集合中元素的个数 9 System.out.println(alist); 10 11 } 12 }
例二:
public class User { }
1 public class TestGeneric { 2 public void test01(Map<String,User> map, List<User> list, String s){ 3 System.out.println("TestGeneric.test01()"); 4 } 5 public Map<Integer,User> test02(){ 6 System.out.println("TestGeneric.test02()"); 7 return null; 8 } 9 public String test03(){ 10 System.out.println("TestGeneric.test03()"); 11 return null; 12 } 13 public static void main(String[] args) throws NoSuchMethodException, SecurityException { 14 //获取test01方法的泛型参数信息 15 Class c=TestGeneric.class; 16 Method test01=c.getMethod("test01", Map.class,List.class,String.class); 17 18 //获取带泛型参数的类型 19 Type [] tytes=test01.getGenericParameterTypes(); 20 System.out.println(tytes.length); //3 21 for (Type type : tytes) { 22 //System.out.println("#"+type); 23 if (type instanceof ParameterizedType) { // 判断是否有泛型 24 Type[] genericType= ((ParameterizedType) type).getActualTypeArguments(); 25 //遍历每一个泛型参数中泛型的类型 26 for (Type genType : genericType) { 27 System.out.println("泛型类型:"+genType); 28 } 29 System.out.println("\n--------------------------"); 30 } 31 } 32 33 System.out.println("\n----------------------------\n"); 34 //获取test02方法返回值的泛型信息 35 Method m2=c.getMethod("test02", null); 36 Type returnType=m2.getGenericReturnType(); 37 //判断是否带有泛型 38 if(returnType instanceof ParameterizedType){ 39 Type [] types=((ParameterizedType) returnType).getActualTypeArguments(); 40 for (Type type : types) { 41 System.out.println("返回值的泛型类型:"+type); 42 } 43 } 44 45 System.out.println("\n------------------------------\n"); 46 Method m3=c.getMethod("test03", null); 47 Type returnType3=m3.getGenericReturnType(); 48 //System.out.println(returnType3); 49 System.out.println(returnType3 instanceof ParameterizedType); //返回值没有泛型,为false 50 } 51 52 }
原文:https://www.cnblogs.com/qiaoxin11/p/12707102.html