This article is continued from the above "Basic Operations of Reflection Method Reflection", using reflection to understand the nature of generics in java collections
1. Initialize two collections, one using generics type, one does not use
1 ArrayList list1 = new ArrayList();2 ArrayList<String> list2 = new ArrayList<String>();
2. If there is a defined type, adding the int type to list2 will report an error
1 list2.add("Hello");2 list2.add(20); //报错
3. Get two Compare the class types of objects
1 Class c1 = list1.getClass();2 Class c2 = list2.getClass();3 System.out.println(c1 == c2);
The c1==c2 result returns true, indicating that the generics of the collection are degenerated after compilation. The generics of the collection in Java are In order to prevent incorrect input, it is only valid during the compilation phase. If you bypass compilation, it will be invalid.
4. Verification: Bypass compilation through method reflection
1 try {2 Method m = c2.getMethod("add", Object.class);3 m.invoke(list2,20);4 System.out.println(list2);5 } catch (Exception e) {6 e.printStackTrace();7 }
5 , Output result
6, Complete code
1 package com.format.test; 2 3 import java.lang.reflect.Method; 4 import java.util.ArrayList; 5 6 /** 7 * Created by Format on 2017/6/4. 8 */ 9 public class Test2 {10 public static void main(String[] args) {11 ArrayList list1 = new ArrayList();12 ArrayList<String> list2 = new ArrayList<String>();13 list2.add("Hello");14 // list2.add(20); //报错15 Class c1 = list1.getClass();16 Class c2 = list2.getClass();17 System.out.println(c1 == c2);18 /**19 * 反射操作都是编译之后的操作20 * c1==c2结果返回true,说明编译之后集合的泛型是去泛型化的21 * java中集合的泛型是为了防止错误输入的,只在编译阶段有效,绕过编译就无效了22 * 验证:通过方法的反射来绕过编译23 */24 try {25 Method m = c2.getMethod("add", Object.class);26 m.invoke(list2,20);27 System.out.println(list2);28 } catch (Exception e) {29 e.printStackTrace();30 }31 }32 }
The above is the detailed content of Reflection: Understanding the essence of collection generics through reflection. For more information, please follow other related articles on the PHP Chinese website!