public class GenericTest {
public static void main(String[] args) throws Exception {
//jdk 1.5 之前
ArrayList collection1 = new ArrayList();
collection1.add(1);
collection1.add(1L);
collection1.add("abc");
//int i = (int) collection1.get(1);
//jdk 1.5以后
ArrayList<String> collection2 = new ArrayList<String>();
//collection2.add(1);
//collection2.add(1L);
collection2.add("abc");
String str = collection2.get(0);
Constructor<String> constructor = String.class.getConstructor(String.class);
String retVal = constructor.newInstance("abc");
System.out.println(retVal);
//ArrayList type of Integer
ArrayList<Integer> collection3 = new ArrayList<Integer>();
/**
* 泛型只是给编译器看的,内存中并没有泛型的概念
*/
System.out.println(collection2.getClass() == collection3.getClass());
//collection3.add("abc"); //编译器报错
//这行代码可以用作泛型的理解
collection3.getClass().getMethod("add", Object.class).invoke(collection3, "abc");
System.out.println(collection3.get(0));
}
}