博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
使用Java反射机制将Map转换为Java对象,支持Boolean、Date类型
阅读量:7029 次
发布时间:2019-06-28

本文共 3274 字,大约阅读时间需要 10 分钟。

  hot3.png

思想: 

在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.     }  

/**

 * 

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

}

}

/**

* <T>

* value

* 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

你可能感兴趣的文章
Redux 源码深度解析(附带视频1月14号上传)
查看>>
理解webpack原理,手写一个100行的webpack
查看>>
Node.js & Express 项目基本搭建
查看>>
掌握 MySQL 这 19 个骚操作,效率至少提高3倍
查看>>
【跃迁之路】【744天】程序员高效学习方法论探索系列(实验阶段501-2019.3.6)...
查看>>
用于大数据测试、学习的测试数据
查看>>
Software System Analysis and Design | 1
查看>>
JavaScript函数式编程,真香之组合(一)
查看>>
JavaScript链式调用实例浅析
查看>>
报表没完没了怎么办? | 润乾集算器提效报表开发
查看>>
记一次Hexo迁移
查看>>
RESTful API 中的 Status code 是否要遵守规范
查看>>
第十一天-《企业应用架构模式》-对象-关系行为模式
查看>>
[spring boot] jdbc
查看>>
新的开始!
查看>>
区块链— 比特币中的区块、账户验证和记账
查看>>
Electron打包,NSIS修改默认安装路径
查看>>
分享一些好用的网站
查看>>
【Android】Retrofit 2.0 的使用
查看>>
Nacos系列:基于Nacos的注册中心
查看>>