Java笔记——泛型擦除

1. 泛型擦除

package cn.Douzi.T_Demo;

import java.util.ArrayList;

/**
 * @Auther: Douzi
 * @Date: 2019/3/8
 * @Description: cn.Douzi.T_Demo
 * @version: 1.0
 */
public class ToolTest {

    public static void main(String[] args) {

        ArrayList<String> a1=new ArrayList<String>();
        a1.add("abc");

        ArrayList<Integer> a2=new ArrayList<Integer>();
        a2.add(123);

        System.out.println(a1.getClass() == a2.getClass());

    }

}

说明泛型类型String和Integer都被擦除掉了,只剩下了原始类型。

泛型本身有一些限制。比如:

那么,利用反射,我们绕过编译器去调用 add 方法。

package cn.Douzi.T_Demo;

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

public class T_demo01 {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        
        List<Integer> a1 = new ArrayList<Integer>();
        a1.add(123);
        
        try {
            Method method = a1.getClass().getDeclaredMethod("add", Object.class);
            
            method.invoke(a1, "test");
            method.invoke(a1, 43.9f);
            
        } catch (NoSuchMethodException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SecurityException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        
        for (Object e : a1) {
            System.out.println(e);
        }

    }

}

这篇博客讲的巨好!收藏一下:https://blog.csdn.net/jeffleo/article/details/52250948 


2. 泛型中的extend和super

这篇博客真棒:https://blog.csdn.net/qq_36898043/article/details/79655309

原文地址:https://www.cnblogs.com/douzujun/p/10498169.html