ImportJava.beans.BeanInfo;Importjava.beans.IntrospectionException;ImportJava.beans.Introspector;ImportJava.beans.PropertyDescriptor;Importjava.lang.reflect.InvocationTargetException;ImportJava.lang.reflect.Method;ImportJava.util.HashMap;ImportJava.util.Map;/*** Created by Fengzhen on 17/3/8.*/ Public classMaptobeanutil {/*** Convert a Map object into a JavaBean *@paramtype to convert *@paramMap containing attribute values *@returnconverted JavaBean Objects *@throwsIntrospectionexception * If parsing class properties failed *@throwsillegalaccessexception * If instantiation of JavaBean failed *@throwsinstantiationexception * If instantiation of JavaBean failed *@throwsInvocationTargetException * If the setter method of the calling property fails*/ Public StaticObject convertmap (Class type, map map)throwsintrospectionexception, Illegalaccessexception, Instantiationexception, invocationtargetexception { BeanInfo BeanInfo= Introspector.getbeaninfo (type);//Get class PropertiesObject obj = type.newinstance ();//Create a JavaBean object//Assigning a value to a property of a JavaBean objectpropertydescriptor[] PropertyDescriptors =beaninfo.getpropertydescriptors (); for(inti = 0; i< propertydescriptors.length; i++) {PropertyDescriptor descriptor=Propertydescriptors[i]; String PropertyName=Descriptor.getname (); if(Map.containskey (PropertyName)) {//The following sentence can be try, so that when a property assignment fails, it does not affect other property assignments. Object value =Map.get (PropertyName); Object[] args=NewObject[1]; args[0] =value; Descriptor.getwritemethod (). Invoke (obj, args); } } returnobj; } /*** Convert a JavaBean object into a Map *@paramJavaBean object to be converted by Bean *@returnthe converted Map Object *@throwsIntrospectionexception If the Parse class property fails *@throwsIllegalaccessexception If instantiating JavaBean failed *@throwsInvocationTargetException If the setter method of the calling property fails*/ Public StaticMap Convertbean (Object Bean)throwsintrospectionexception, Illegalaccessexception, invocationtargetexception {Class type=Bean.getclass (); Map Returnmap=NewHashMap (); BeanInfo BeanInfo=introspector.getbeaninfo (type); Propertydescriptor[] PropertyDescriptors=beaninfo.getpropertydescriptors (); for(inti = 0; i< propertydescriptors.length; i++) {PropertyDescriptor descriptor=Propertydescriptors[i]; String PropertyName=Descriptor.getname (); if(!propertyname.equals ("Class") {Method Readmethod=Descriptor.getreadmethod (); Object result= Readmethod.invoke (Bean,NewObject[0]); if(Result! =NULL) {returnmap.put (propertyname, result); } Else{returnmap.put (propertyname,""); } } } returnReturnmap; }}
Java Map and Bean transformation