使用Java反射机制将Map转换为Java对象,支持Boolean、Date类型

思想: 
在web应用的构建中,若使用ajax对前台数据进行封装,成键值对的形式(如,保存在request中的值),传递给后台时自动装配成一个对象。同时适用于多个form往后台传数据

测试类

  1. public static void main(String[] args) {  

  2.         Map<String,Object>  request= new HashMap<String,Object>();  

  3.         request.put("id""001");  

  4.         request.put("name""Kill");  

  5.         request.put("sex""false");  

  6.         request.put("birthday","2012-07-17 16:45:12");  

  7.           

  8.         User user = ReflectUtils.getBean(request, User.class);  

  9.           

  10.         System.out.println(user.toString());  

  11.           

  12.     }  

/**

 * 

 * @author duof

 *  转换类

 */

public class ReflectUtils {

@SuppressWarnings("unchecked")

public static <T> T getBean(Map<String,Object> param , Class clazz){

Object value = null;

Class[] paramTypes = new Class[1];

Object obj = null;

try {

//创建实例

obj = clazz.newInstance();

Field[] f = clazz.getDeclaredFields();

List<Field[]> flist = new ArrayList<Field[]>();

flist.add(f);

Class superClazz = clazz.getSuperclass();

while(superClazz != null){

f = superClazz.getDeclaredFields();

flist.add(f);

superClazz = superClazz.getSuperclass();

}

for (Field[] fields : flist) {

for (Field field : fields) {

String fieldName = field.getName();

value = param.get(fieldName);

if(value != null){

paramTypes[0] = field.getType();

Method method = null;

//调用相应对象的set方法

StringBuffer methodName = new StringBuffer("set");

methodName.append(fieldName.substring(0, 1).toUpperCase());

methodName.append(fieldName.substring(1, fieldName.length()));

//测试输出

System.out.println(paramTypes[0].getName());

method = clazz.getMethod(methodName.toString(), paramTypes);

method.invoke(obj, ConvertUtil.getValue(value.toString(), fieldName, paramTypes[0]));

}

}

}

} catch (InstantiationException e) {

e.printStackTrace();

} catch (IllegalAccessException e) {

e.printStackTrace();

} catch (SecurityException e) {

e.printStackTrace();

} catch (NoSuchMethodException e) {

e.printStackTrace();

} catch (IllegalArgumentException e) {

e.printStackTrace();

} catch (InvocationTargetException e) {

e.printStackTrace();

}

return (T)obj;

}

}


//  辅助类

public class ConvertUtil {

public static<T> T getValue(String value,String fieldName,Class<T> clazz){

if (value == null) { // 如果获取参数值为null,则返回null

return null;

} else if (!value.equals("")) { // 如果获取参数值不为"",则通过convertGt方法进行类型转换后返回结果

return convertGt(value, clazz);

} else if (clazz.getName().equals(String.class.getName())) { // 如果获取参数值为""

return convertGt(value, clazz);

} else {// 如果获取参数值为"",并且clazz不是是String类型,则返回null

return null;

}

}

/**

* @param <T>

* @param value

* @param clazz

* @return

*/

@SuppressWarnings("unchecked")

public static <T> T convertGt(String value, Class<T> clazz) {

if (value == null) { // 如果值为null,则返回null

return null;

} else if (value.equals("")

&& !clazz.getName().equals(String.class.getName())) { // 如果value值为"",而且要转为的类型不是string类型,那么就统一返回null,也就是空字符串不能转成任何其他类型的实体,只能返回null

return null;

} else if (Date.class.getName().equalsIgnoreCase(clazz.getName())) { // 增加对从String类型到Date

return (T) convertSTD(value);

}

return (T) ConvertUtils.convert(value, clazz);

}


//日期类型的转换

private static SimpleDateFormat simpleDateFormate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

public static Date convertSTD(String date){

try {

return simpleDateFormate.parse(date);

} catch (ParseException e) {

e.printStackTrace();

}

return null;

}

public static String convertDTS(Date date){

return simpleDateFormate.format(date);

}

}



转载于:https://my.oschina.net/duof/blog/338478

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值