import java.lang.reflect.Field;import java.lang.reflect.InvocationTargetException;import java.lang.reflect.Method;import java.util.Map;import sdcncsi.ict.util.RequestUtil;/** * 反射类将Map转换为bean; * @author mywhile * * @param <T> */@SuppressWarnings("unchecked")public class YdxsRequestUtil<T> { public static <T> T convertToBean(Map map, T obj) throws SecurityException, NoSuchMethodException, IllegalArgumentException, InstantiationException, IllegalAccessException, InvocationTargetException { Class<?> classType = obj.getClass(); Field[] fields = classType.getDeclaredFields();//得到对象中的字段 //每次循环时,重新实例化一个与传过来的对象类型一样的对象 T oCopy = (T) classType.getConstructor(new Class[] {}).newInstance(new Object[] {}); for(int i=0;i<fields.length;i++){ System.out.println(fields[i].getName()); Field field = fields[i]; String fName = fields[i].getName(); Object value = null; if (field.getType().equals(String.class)) { value = String.valueOf(map.get(fName)); if (value == null || value.equals("null")) { value = ""; } } /* if (field.getType().equals(int.class)) { value = String.valueOf(map.get(fName)); value = Integer.valueOf((value == null || value.equals("null")) ? "1" : "0"); } if (field.getType().equals(java.util.Date.class)) { value = Date.valueOf(String.valueOf(map.get(fName))); } */ // 获得属性的首字母并转换为大写,与setXXX对应 String firstLetter = fName.substring(0, 1).toUpperCase(); String setMethodName = "set" + firstLetter + fName.substring(1); Method setMethod = classType.getMethod(setMethodName, new Class[] { field.getType() }); setMethod.invoke(oCopy, new Object[] { value });// 调用对象的setXXX方法 } return oCopy; }}
?Map ====> Bean
bean = YdxsRequestUtil.convertToBean(map, bean);