Java uses generics to transform the Bean class and map

Source: Internet
Author: User
Tags map class

Java uses generics to transform the Bean class and map, and the use of generics can bring many benefits:

The first is type safety, the type safety of Java programs. By knowing that generics are used, these assumptions exist only in the programmer's mind (or, if you're lucky, in code comments).

generics allow the compiler to enforce these additional type constraints. Type errors can now be captured at compile time, rather than being shown as classcastexception at run time.

Moving type checking from runtime to compile can help you find errors more easily and improve the reliability of your program.

Eliminates forced type conversions. A side benefit of generics is the elimination of many coercion type conversions in the source code. This makes the code more readable and reduces the chance of error.

The Main method actually:

1  Public classBeanutil {2 3      Public Static voidMain (string[] args)throwsException {4 5Map<string, object> MP =NewHashmap<string, object>();6Mp.put ("name", "Jack");7Mp.put ("Age", 40);8Mp.put ("MN", "male");9 TenPersonbean person = Map2bean (MP, Personbean.class); OneSystem.out.println ("Transmap2bean Map Info:"); A          for(Map.entry<string, object>Entry:mp.entrySet ()) { -System.out.println (Entry.getkey () + ":" +Entry.getvalue ()); -         } theSystem.out.println ("Bean Info:"); -System.out.println ("Name:" +person.getname ()); -System.out.println ("Age:" +person.getage ()); -System.out.println ("MN:" +person.getmn ()); +  - Bean2map (person, MP); +System.out.println ("Transbean2map Map Info:"); A          for(Map.entry<string, object>Entry:mp.entrySet ()) { atSystem.out.println (Entry.getkey () + ":" +Entry.getvalue ()); -         } -}

Maptobean Method:

1      Public Static<t, K, v> T Map2bean (map<k, v> MP, class<t>beancls)2             throwsException, IllegalArgumentException, invocationtargetexception {3T t =NULL;4         Try {5 6BeanInfo BeanInfo =Introspector.getbeaninfo (BEANCLS);7propertydescriptor[] PropertyDescriptors =beaninfo.getpropertydescriptors ();8 9t =beancls.newinstance ();Ten  One              for(PropertyDescriptor property:propertydescriptors) { AString key =property.getname (); -  -                 if(Mp.containskey (key)) { theObject value =Mp.get (key); -Method setter = Property.getwritemethod ();//Java provides access to a property in the -                                                                 //Getter/setter Method - Setter.invoke (t, value); +                 } -             } +  A}Catch(introspectionexception e) { at  - e.printstacktrace (); -         } -         returnT; -}

Beantomap Method:

1  Public Static<t, K, v> map<string, object> bean2map (T Bean, map<string, object>MP)2             throwsException, illegalaccessexception {3 4         if(Bean = =NULL) {5             return NULL;6         }7 8         Try {9BeanInfo BeanInfo =Introspector.getbeaninfo (Bean.getclass ());Tenpropertydescriptor[] PropertyDescriptors =beaninfo.getpropertydescriptors (); One  A              for(PropertyDescriptor property:propertydescriptors) { -String key =property.getname (); -  the                 if(!key.equals ("Class")) { -  -Method getter = Property.getreadmethod ();//Java provides access to a property in the -                                                                 //Getter/setter Method + Object value; -  +Value =Getter.invoke (bean); A mp.put (key, value); at                 } -  -             } -  -}Catch(introspectionexception e) { -  in e.printstacktrace (); -}Catch(Illegalaccessexception | IllegalArgumentException |invocationtargetexception e) { to             //TODO auto-generated Catch block + e.printstacktrace (); -  the         } *         returnMP; $ Panax Notoginseng     } -}

Summary: Using generics avoids type conversion mistakes, and you can see the motivations for generics in the collection Framework (Collection framework). For example, the map class allows you to add an object of any class to a map.

Even the most common scenario is to save an object of a particular type (such as a String) in a given map (map). Because Map.get () is defined to return an Object, it is generally necessary to cast the result of Map.get () to the desired type, as shown in the following code:

Map m = new HashMap ();
M.put ("Key", "Blarg");
string s = (string) m.get ("key");

For the program to compile, you must cast the result of the Get () to string, and you want the result to be really a string. But it is possible that someone has saved something that is not a String in the map, so the above code will throw classcastexception.

Java implements the transformation of bean classes and maps using generics

Related Article

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.