泛型擦除机制及相关问题

一、类型擦除

public class A<T> {
   
    private T value;
    public T getValue() {
   
        return value;
    }
    public void setValue(T value) {
   
        this.value = value;
    }
}

//编译后
public class A
{
   
	private Object value;
	public Object getValue() {
   
		return value;
	}
	public void setValue(Object value) {
   
		this.value = value;
	}
}

所以,运行时进行类型查询的时候使用下面的方法是错误的

@Test
public void test3() {
   
    ArrayList<String> arrayList=new ArrayList<>();
    if (arrayList instanceof ArrayList<String>) {
    //illegal generic type instanceof
        System.out.println("ture");
    }
}

二、类型擦除时机

@Test
public void test1() {
   
    A<String> stringA = new A<>();
    A<Integer> integerA = new A<>();
    System.out.println(stringA.getClass()==integerA.getClass());
}

//打印
true

说明泛型的擦除是在编译前,jvm会将其看做同一个普通类Object进行处理

三、类型检查时机

@Test
public void test3() {
   
    ArrayList<String> arrayList=new ArrayList<String>();
    arrayList.add("123");
    arrayList.add(123);//编译错误
}

先检查泛型类型,再擦除,再编译,保证我们只能使用泛型变量限定的类型进行操作。

@Test
public void test2() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
   
    ArrayList&l
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值