泛型擦除

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