首先,它是在org.apache.commons.beanutils.BeanUtils包中的一个方法。
InsuranceInfo info = newInsuranceInfo();
(这是一个javabean)
BeanUtilities.populateBean(info, request);
方法的作用:用来将一些 key-value 的值(例如 hashmap)映射到 bean 中的属性。
servlet中有这样的使用:
先定义form表单内容的Info对象(当然你要先写一个bean,这个bean中包含form表单中各个对象的属性)
——> populateBean(info,request.getParameterMap());(先将request内容转为Map类型)
——>BeanUtils.populate(info,propertyMap);(调用包中方法映射)
映射的过程就是将页面中的内容先用request获得,然后再将之转换为Map(这里用request.getParameterMap())
最后使用BeanUtils.populate(info,map)方法将页面各个属性映射到bean中。之后我们就可以这样使用bean.getXxxx()来取值了。
package playecsp.utils; import java.beans.BeanInfo; import java.beans.Introspector; import java.beans.PropertyDescriptor; import java.lang.reflect.Method; import java.util.HashMap; import java.util.Map; public class BeanUtils extends org.apache.commons.beanutils.BeanUtils { /** * Map转换成对象(使用apache commons实现) * @param map * @param t * @param <T> * @return */ public static <T> T map2Bean(Map<String, Object> map, T t) { if(map == null || t == null) { return null; } try{ org.apache.commons.beanutils.BeanUtils.populate(t, map); } catch (Exception e) { e.printStackTrace(); } return t; } /** * Map转换成对象(JDK实现) * @param map * @param t * @param <T> * @return */ public static <T> T map2BeanJava(Map<String, Object> map, T t) { if(map == null || t == null) { return null; } try { BeanInfo beanInfo = Introspector.getBeanInfo(t.getClass()); PropertyDescriptor[] pds = beanInfo.getPropertyDescriptors(); for(PropertyDescriptor pd : pds) { String key = pd.getName(); if(map.containsKey(key)) { Object value = map.get(key); Method setter = pd.getWriteMethod(); setter.invoke(t, value); } } } catch (Exception e) { e.printStackTrace(); } return t; } /** * 对象转换成Map(JDK实现) * @param obj * @return */ public static Map<String, Object> bean2MapJava(Object obj) { if(obj == null) { return null; } Map<String, Object> rtnMap = new HashMap<>(); try{ BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass()); PropertyDescriptor[] pds = beanInfo.getPropertyDescriptors(); for(PropertyDescriptor pd : pds) { String key = pd.getName(); if(!key.equals("class")) { Method getter = pd.getReadMethod(); Object value = getter.invoke(obj); rtnMap.put(key, value); } } } catch (Exception e) { e.printStackTrace(); } return rtnMap; } public static void tests() { //EntityA ea = EntityA.findByID(id); //EntityAHis nah = new EntityAHis(); //org.apache.commons.beanutils.BeanUtils.copyProperties(nah, nae); } }