List<String>转换为实体类的属性【转】
2016-06-14 08:57
405 查看
package model; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; public class ListToModel { public static void main(String[] args) { List<Object> userList = new ArrayList<Object>(); userList.add("ooP"); userList.add("男"); userList.add(18); User user = new User(); try { listToModel(userList, user); } catch (Exception e) { e.printStackTrace(); } System.out.println(user.getName() + "; " + user.getGender() + "; " + user.getAge()); } public static <T> void listToModel(List<Object> list, T t) throws Exception { Field[] fields = t.getClass().getDeclaredFields(); if (list.size() != fields.length) { return; } for (int k = 0, len = fields.length; k < len; k++) { // 根据属性名称,找寻合适的set方法 String fieldName = fields[k].getName(); String setMethodName = "set" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1); Method method = null; Class<?> clazz = t.getClass(); try { method = clazz.getMethod(setMethodName, new Class[] { list.get(k).getClass() }); } catch (SecurityException e1) { e1.printStackTrace(); return; } catch (NoSuchMethodException e1) { String newMethodName = "set" + fieldName.substring(0, 1).toLowerCase() + fieldName.substring(1); try { method = clazz.getMethod(newMethodName, new Class[] { list.get(k).getClass() }); } catch (SecurityException e) { e.printStackTrace(); return; } catch (NoSuchMethodException e) { e.printStackTrace(); return; } } if (method == null) { return; } method.invoke(t, new Object[] { list.get(k) }); } } }
相关文章推荐
- CentOS x64上Matlab R2015b的镜像安装方法与卸载
- [ solr入门 ] - 利用solrJ进行检索
- Chrome浏览器快捷键大全
- <<Effective C++>>读书笔记8: 定制new和delete
- linux配置ssh互信
- 前后端分离开发模式下后端质量的保证 —— 单元测试
- eclipse集成tomcat后修改java内存
- ListView适配不同item范例
- Android组件(Broadcast Receiver)
- java-json日期字符串转换
- 有5个人坐在一起,问第五个人多少岁?他说比第4个人大2岁。问第4个人岁数,他说比第3个人大2岁。问第三个人,又说比第2人大两岁。问第2个人,说比第一个人大两岁。最后问第一个人,他说是10岁。请问第五个人多大?
- Google免费DNS服务器IP及全国主要DNS
- javascript--第九节-爱奇艺网站首页(轮播图)
- hdoj 1237 简单计算器《栈》
- DB2 SQL Error: SQLCODE=-668, SQLSTATE=57016错误解决方法
- javascript-第九节-键值或按钮控制div移动、轮播
- 接口的注意事项
- python 占位符 %s Format
- python sys os hashlib_MD5 模块
- Java使用Apache POI库读取Excel表格文档的示例