Reflection: understanding the nature and nature of a set of generics through reflection
This article introduces "basic operations of Reflection Method reflection", and uses reflection to understand the nature of generics in java sets.
1. initialize two sets. One uses the generic type and the other does not.
1 ArrayList list1 = new ArrayList();2 ArrayList<String> list2 = new ArrayList<String>();
2. If you have a defined type, you can add the int type to list2. An error is returned.
1 list2.add ("Hello"); 2 list2.add (20); // Error
3. Obtain the class types of the two objects for comparison.
1 Class c1 = list1.getClass();2 Class c2 = list2.getClass();3 System.out.println(c1 == c2);
Return true through c1 = c2, indicating that the generic type of the set after compilation is de-Generic. The generic type integrated in java is used to prevent incorrect input, it is valid only in the compilation phase and does not work if compilation is bypassed.
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 results
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 keys /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 ); // error 15 Class c1 = list1.getClass (); 16 Class c2 = list2.getClass (); 17 System. out. println (c1 = c2); 18/** 19 * reflection operations are all compiled Operations 20 * c1 = c2 and return true, it indicates that the generic type of the set after compilation is de-generic 21 * the generic type integrated in java is used to prevent incorrect input and is only valid during the compilation phase, 22 * Verification is invalid when compilation is bypassed. Verification: The Method reflection bypasses compilation by 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}
View Code