使用反射绕过泛型,直接赋值

基本的泛型:

public class GenericsTest {
 public static void main(String[] args) {
  ArrayList<String> collection1 = new ArrayList();
  collection1.add("abc");
  String str1 = collection1.get(0);
  System.out.println(str1);
  
  ArrayList<Integer> collection2 = new ArrayList();
  collection2.add(3);
  int int2 = collection2.get(0);
  System.out.println(int2);
 }

}

输出结果很明显是abc和3

现在用放射看看他们的字节码是不是同一份:

在程序中加入下面代码:

System.out.println(collection1.getClass()==collection2.getClass());

这行代码的输出结果是true------说明ArrayList虽然有不同的泛型在内存中字节码只有一份,就是编译完成之后就没有类型信息了,已经去类型化了,为了证明这个可以行,用反射向ArrayList<Integer> collection2 = new ArrayList();中增加String类型的对象。

首先若是直接collection2.add("abc");编译器肯定是会报错的。因为collection2是integer类型的。

下面用反射进行实验: 
 输出结果为:

abc

3

true

abc
  

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值