There are generics in the previously learned set, and after the generic type is specified, it is not possible to add type data to this collection except for this type.
So, what can I do to get over this generic and add type data other than a specific type?
Example:
Adds a string to the Arraylist<integer> collection of data
Analysis:
By looking at the Add () method of the ArrayList, you know, add (e). E This generic is object.
You can directly invoke the Add method of the ArrayList collection by using reflection.
1 Public Static voidMain (string[] args)throwsException {2 3 // Create ArrayList collection Object 4arraylist<integer> array =NewArraylist<integer>();5 6 //directly add definitely not7 //array.add ("Hello");8 9 //by looking at the Add () method of the ArrayList, you know, add (e). E This generic is object. Ten //You can directly invoke the Add method of the ArrayList collection by using reflection. One A // Gets the class byte file object for the ArrayList collection -Class C =Array.getclass (); - //To get the Add method, the method requires a parameter that is the object class theMethod m = C.getmethod ("Add", Object.class); - //call the Add method to add "XXX" using the Add method of array (allaylist) -M.invoke (Array, "Hello"); -M.invoke (Array, "World"); + -SYSTEM.OUT.PRINTLN (array);//[Hello, World] + A}
Java 27-7 reflection crosses the generic check through reflection