使用反射繞過泛型,直接賦值

基本的泛型:

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
  

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章