Generics are provided to the Javac compiler to qualify the input types in the collection, let the compiler block illegal input in the source program, and the compiler compiles a collection of type descriptions to remove the "type" information, which makes the program run efficiently unaffected.
Because the compiled bytecode removes the generic type information, as long as it can skip the compiler, you can add other types of data to a generic collection. So we can add other types of data to the generic collection with reflection. Example 1:
Arraylist<integer> ArrayList =NewArraylist<integer>(); ArrayList. Add (Ten); ArrayList. Add ( -); ArrayList. GetClass (). GetMethod ("Add", Object.class). Invoke (ArrayList,"HBase"); System. out. println (ArrayList.Get(2));//Although the location of index 2 is a string type, the compile-time compiler considers ArrayList. Get (2) to return an integer type, but is still//s when the value is run Tring Type
Output: HBase
Example 2:
Arraylist<string> ArrayList =NewArraylist<string>(); Arraylist1.add ("Hadopp"); Arraylist1.add ("Hive"); Arraylist1.getclass (). GetMethod ("Add", Object.class). Invoke (ArrayList1, -); System. out. println (ArrayList1.Get(2));//Although the location of index 2 is an integer type,However, the compile-time compiler will consider ArrayList. Get (2) to return a string type, but still//integer type when the value is run
"Main" Java.lang.ClassCastException:java.lang.Integer cannot is cast to java.lang.String at Com.mobin.generic.GenericTest.main (Generictest.java:20)
Error code: SYSTEM.OUT.PRINTLN (Arraylist1.get (2));integer cannot be converted to string, but example 1 is not reportedWhat about the classcastexception anomaly? (You can also think of what the reason is to look at the following analysis) the following analysis of the reason: the occurrence of classcastexception this exception can be concluded that the type of conversion errors. The reason is that the SYSTSTEM.OUT.PRINTLN statement, which is the println () of all overloaded methods, except the Bool,char,char[],double,float,int,string,long type, The println (object) method is called when the passed parameter is treated as an object when it is another type. In Example 1, because Arraylist1.get (2) returns an integer, it is called the println (object) method, which verifies that the mouse is placed on the println method. OK, let's go back to println (object x) The source code to see the parameters are automatically turned into a string type!!! Equivalent to Object x = Arraylist.get (2); All objects belong to object String s = string.valueof (x), so there is no error. Look at the second code of the println call is println (string x), the same into the source to see: the equivalent of String x = Arraylist.get (2); The type of the value at run time Arraylist.get (2) is Integer and is equivalent to string x = integer;
Issues encountered when adding other types of data to a generic collection using reflection