Java provides a java.beans.Introspector class that helps us analyze which properties are in the JavaBean class, which makes it easy to value and assign JavaBean object properties. The following is an example of creating a JavaBean object based on the contents of the Map object.
01.import Java.beans.BeanInfo;
02.import java.beans.IntrospectionException;
03.import Java.beans.Introspector;
04.import Java.beans.PropertyDescriptor;
05.import Java.util.HashMap;
06.import Java.util.Map;
07.import java.lang.reflect.InvocationTargetException;
09.public class Maptobean {10. One. public static void Main (string[] args) throws Exception {12.
Map<object, object> map = new Hashmap<object, object> ();
Map.put ("name", "John");
Map.put ("Age", 30);
Person p = convertmap (person.class, map);
System.out.println (P.getname () + "," + p.getage ());
17.} 18. 19./** 20. * Converts a Map object to a JavaBean 21. * 22. * @param Type 23 to convert. * The @param map contains the property value of Map 24. * 25. * @return Transformed the JavaBean object 26. * 27. * @throws Introspectionexception if parsing class property fails 28. * @throws illegalaccessexception If instantiating JavaBean fails 29. * @throws instantiationexception If instantiating JavaBean fails 30. * @throws InvocationTargetException If the setter method of the calling property fails 31. * * 32. private static <T> T convertmap (class<t> type, map<object, object> Map) 33. Throws Introspectionexception, Illegalaccessexception, 34. Instantiationexception, InvocationTargetException {35. BeanInfo BeanInfo = Introspector.getbeaninfo (type); Gets the class property 36. T t = type.newinstance ();
Create JavaBean Object 37. 38.//Give the property of the JavaBean object a value of 39. For (PropertyDescriptor descriptor:beanInfo.getPropertyDescriptors ()) {40.
String propertyname = Descriptor.getname (); if (Map.containskey (PropertyName)) {42.
The following sentence can be try, so that when a property assignment fails, it does not affect other property assignments.
Descriptor.getwritemethod (). Invoke (T, Map.get (PropertyName)); 44.} 45. } 46.
return t;
47.} 48.}
50.class Person {51.
private String name; 53.54.
private int age; 55.56. Public String GetName() {; return name;
58.} 59. public void SetName (String name) {61.
THIS.name = name;
62.} 63. public int getage () {65.
return age;
66.} 67. public void Setage (int age) {69.
This.age = age; 70.} 71.}