Reprint Please specify : Http://blog.csdn.net/uniquewonderq
Understanding the nature of generics through Class,method
the actions that are reflected are all compiled operations, that is, operation time
C1==C2 results return True, after compilation, the generic of the collection is de-generics
It means that this collection has no generics after compilation.
The generics in the Java collection are prevented from being incorrectly entered, only valid during the compile phase,
The compilation is not valid.
Validation: We can manipulate the reflection of the method, bypassing the compilation
Package com.test; Import Java.lang.reflect.Method; Import java.util.ArrayList; /** * * @author WONDERQ */public class within {public static void main (string[] args) { ArrayList list=new ArrayList (); Arraylist<string> list1=new arraylist<string> (); List1.add ("Hello"); List1.add (5); The wrong Class C1=list.getclass (); Class C2=list1.getclass (); System.out.println ("C1==c2? "+ (C1==C2)); SYSTEM.OUT.PRINTLN ("C1 and C2 are:" +c1.getname () + "," +c2.getname ()); /* The reflected operation is the post-compilation operation, that is, the run-time operation C1==C2 The result returns true, stating that after compilation, the generic of the collection is de-generalized, that is, the collection is not generic after compilation. Generics in a collection in Java are prevented from being entered incorrectly, only in the compile phase, and it is not valid to compile. Validation: We can operate through the reflection of the method, bypassing the compilation */try {Method M=c2.getmethod ("Add", Object.class); M.invoke (List1, 100);//originally included in the string type of object, now add a 100//Let's see if we can add it in. System.out.println (List1.size ()); System.out.println (List1); Can be added, and now bypasses generics, because the action of reflection is compiled after the operation for (string string:list1) {System.out.println (string) ; }//at this time cannot print out the int type of the 100 this number} catch (Exception e) {}}}
Operation Result:
Run
C1==c2? True
C1 and C2 were: java.util.arraylist,java.util.arraylist
2
[Hello, 100]
Hello
It can be seen that the action of reflection, class
, method, etc., are all bypassing compilation and running at run time.
Java--reflect (reflection) thematic 6--understanding the nature of set generics by reflection