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

Source: Internet
Author: User

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

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.