泛型实现机制

发布于 2021-06-15  82 次阅读


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

public class MyObject {
    public static void main(String[] args) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        int i = 666;
        Object obj = i;
        System.out.println(obj);

        List<String> list = new ArrayList<>();
        list.add("aaa");
        list.add("bbb");
        // 编译器会阻止
        // list.add(333);

        // 但泛型约束只存在于编译期,底层仍是Object,所以运行期可以往List存入任何类型的元素
        Method addMethod = list.getClass().getDeclaredMethod("add", Object.class);
        addMethod.invoke(list, 333);

        // 打印输出观察是否成功存入Integer(注意用Object接收)
        for (Object l : list) {
            System.out.println(l);
        }
    }
}

反编译后

//Class文件
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class MyObject {
    public MyObject() {
    }

    public static void main(String[] args) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        int i = 666;
        Object obj = Integer.valueOf(i);
        System.out.println(obj);
        List<String> list = new ArrayList();
        list.add("aaa");
        list.add("bbb");
        Method addMethod = list.getClass().getDeclaredMethod("add", Object.class);
        addMethod.invoke(list, 333);
        Iterator var5 = list.iterator();

        while(var5.hasNext()) {
            Object l = var5.next();
            System.out.println(l);
        }

    }
}