Java-understanding the nature of collection generics through reflection

The generics of collections in Java are to prevent erroneous input, and are only valid during the compilation phase, and bypassing the compilation to the runtime is invalid.

Let's verify by an example

/**
 * The essence of collection generics
 * @description
 * @author Trigl
 * @date 2:54:11 AM on April 2, 2016
 */
public class GenericEssence {
    public static void main(String[] args) {
        List list1 = new ArrayList (); // No generic 
        List <String> list2 = new ArrayList <String> (); // There is generic


        /*
         * 1. First observe the normal way of adding elements, check the generics in the compiler,
         * At this time, if int type is added to list2, an error will be reported
         * / 
        list2.add ( "hello" );
 //       list2.add (20); // Report an error! List2 has a generic limitation, you can only add String, add int error 
        System.out.println ("The length of list2 is:" + list2.size ()); // The length of list2 is 1


        /*
         * 2. Then add elements by reflection, dynamically load the class at runtime, first get list1 and list2
         * The class type is the same, and then bypass the compiler through method reflection to call the add method to see if you can insert int
         * Elements of type
         */
        Class c1 = list1.getClass();
        Class c2 = list2.getClass();
        System.out.println (c1 == c2); // Result: true, indicating that the class types are exactly the same

        // Verify: We can add elements to list2 through the reflection of the method, so that we can bypass the compilation check 
        try {
            Method m = c2.getMethod ("add", Object. Class ); // Get the add method by method reflection 
            m.invoke (list2, 20); // Add an int type to list2, which is shown above in the compiler being given 
            System.out.println ( "length list2 is:" + list2.size ()); // results: 2, described list2 length increases, and there is no generic check 
        } the catch (Exception E) {
            e.printStackTrace ();
        }

        /*
         * In summary, it can be seen that in the compiler, generics will restrict the element types in the collection to remain consistent, but the compiler ends
         * After the runtime, generics will no longer work, even elements of different types can be inserted into the collection.
         */
    }
}

 

Guess you like

Origin www.cnblogs.com/xingchong/p/12723950.html