1 PackageCom.tn.collect;2 3 ImportJava.lang.reflect.Method;4 Importjava.util.ArrayList;5 6 Public classFanxin {7 Public Static voidMain (string[] args) {8 //the role of generics is to prevent incorrect input during the compilation phase, bypassing the generics9 //reflection is all about bypassing the compilation operationTenArraylist<string> str=NewArraylist<string>(); OneStr.add ("Hello! "); AArrayList str2=NewArrayList (); - - //The result is true to indicate that the class type is the same, and that after compilation it is de-generalized theSystem.out.println (str.getclass () = =Str2.getclass ()); -System.out.println (Str.getclass () ==arraylist.class); - - //reflection with the Add method + Try{ -Method Method=str.getclass (). GetMethod ("Add",NewClass[]{object.class}); +Method.invoke (str,Newobject[]{100}); A}Catch(Exception e) { at e.printstacktrace (); - } - - System.out.println (Str.size ()); - System.out.println (str); - in for(String s:str) { - System.out.println (s); to } + } -}View Code
Operation Result:
True
True
2
Hello , 100]
How are you doing!
Exception in thread "main" Java.lang.ClassCastException:java.lang.Integer cannot is cast to java.lang.String
At Com.tn.collect.Fanxin.main (fanxin.java:29)
The role of the "Java" Generics is to prevent erroneous input during the compilation phase, bypass the generics by bypassing the compilation, and use reflection validation