Java 27-7 reflection crosses the generic check through reflection

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.