首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 网站开发 > Web前端 >

Java反照Bean

2013-02-18 
Java反射Beanimport java.lang.reflect.Fieldimport java.lang.reflect.InvocationTargetExceptionimpor

Java反射Bean

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);

热点排行