[javaEE] 反射-通过反射了解集合泛型本质详解编程语言

java中的泛型是防止错误输入的,只在编译时刻起作用

package com.tsh.reflect; 
 
import java.lang.reflect.Method; 
import java.util.ArrayList; 
 
 
 
public class ReflectDemo { 
    public static void main(String[] args) { 
        ArrayList list=new ArrayList(); 
        ArrayList<String> list2=new ArrayList<String>(); 
        list.add("tsh"); 
        list.add(2); 
         
        list2.add("tsh"); 
        //list2.add(2);//直接编译不通过,会报错 
         
        //泛型检测只是在编译时刻才会有,绕过编译时刻,就不存在泛型了 
        Class c2=list2.getClass(); 
        try { 
            Method m=c2.getMethod("add", Object.class); 
            m.invoke(list2, 2);//绕过编译时刻,此时这个泛型检查不起作用,int型也能加进去了 
            System.out.println(list2.size());//2个元素 
            //此时不能使用for(String str:list2)这个遍历,会报类型转换异常 
        } catch (Exception e) { 
            e.printStackTrace(); 
        } 
    } 
}

 

原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/industrynews/12620.html

(0)
上一篇 2021年7月19日 14:45
下一篇 2021年7月19日 14:45

相关推荐

发表回复

登录后才能评论