Packagecn.itsource.crm.utils;ImportJava.beans.PropertyDescriptor;ImportJava.lang.reflect.Method;ImportJava.lang.reflect.Modifier;ImportJava.util.HashMap;ImportJava.util.Map;Importorg.springframework.beans.BeanUtils; Public classCommutil {/*** Encapsulates the specified complex object properties into a new map according to the specified content *@paramSource target Object *@paramPS needs to encapsulate attributes in map *@return */ Public StaticMap<string, object>Obj2map (Object source, string[] PS) {Map<string, object> map =NewHashmap<>(); if(Source = =NULL) return NULL; if(PS = =NULL|| Ps.length < 1) { return NULL; } for(String p:ps) {PropertyDescriptor SOURCEPD=Beanutils.getpropertydescriptor (Source.getclass (), p); if(SOURCEPD! =NULL&& Sourcepd.getreadmethod ()! =NULL) { Try{Method Readmethod=Sourcepd.getreadmethod (); if(!Modifier.ispublic (Readmethod.getdeclaringclass (). getmodifiers ())) {readmethod.setaccessible (true); } Object Value= Readmethod.invoke (Source,NewObject[0]); Map.put (p, value); } Catch(Exception ex) {Throw NewRuntimeException ("Could not copy properties from source to target", ex); } } } returnmap; } }
Object properties encapsulated in Map