首页 > 其他 > 详细

泛型擦除

时间:2019-07-04 19:18:53      阅读:79      评论:0      收藏:0      [点我收藏+]
package com.zy.exercise;

import java.lang.reflect.Method;
import java.util.ArrayList;

public class exercise {

    public static void main(String[] args) throws Exception{
        
        //泛型只存在编译阶段,会进行泛型检查,编译结束后,泛型会自动擦除    
        ArrayList<Integer> arrayList = new ArrayList<>();
        arrayList.add(10);
        
        
        //反射去拿add方法(绕过编译阶段的泛型检查直接去拿add方法)
        //1得到class对象
        Class class1=arrayList.getClass();
        //2得到method对象
        Method declaredMethod = class1.getDeclaredMethod("add",Object.class);
        //3调用方法
        
        declaredMethod.invoke(arrayList, ‘A‘);
        declaredMethod.invoke(arrayList, 0.3);
        declaredMethod.invoke(arrayList, "中国");
        
        //验证
        for (int i = 0; i < arrayList.size(); i++) {
            System.out.println(arrayList.get(i));
            
        }
    
    }

}

运行结果

技术分享图片

泛型擦除

原文:https://www.cnblogs.com/qfdy123/p/11134021.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!