用反射原理 , 将ResultSet的结果放到java对象中, 通用公共方法

用反射原理 , 将ResultSet的结果放到java对象中, 通用公共方法. 详解在方法中 

public static <T> ArrayList<T> putResult(ResultSet rs, Class<T> obj) throws FrameException {
		try {
			ArrayList<T> arrayList = new ArrayList<T>();
			ResultSetMetaData metaData = rs.getMetaData();
			//获取总列数,确定为对象赋值遍历次数
			int count = metaData.getColumnCount();
			while (rs.next()) {
				// 创建对象实例
				T newInstance = obj.newInstance();
				// 开始为一个对象赋值
				for (int i = 1; i <= count; i++) {
					// 给对象的某个属性赋值
					String name = metaData.getColumnName(i).toLowerCase();
					// 改变列名格式成java命名格式
					name = toJavaField(name);
					// 首字母大写
					String substring = name.substring(0, 1);
					String replace = name.replaceFirst(substring, substring.toUpperCase());
					// 获取字段类型
					Class<?> type = obj.getDeclaredField(name).getType();
					Method method = obj.getMethod("set" + replace, type);
					//判断读取数据的类型
					if (type.isAssignableFrom(String.class)) {
						method.invoke(newInstance, rs.getString(i));
					} else if (type.isAssignableFrom(int.class) || type.isAssignableFrom(Integer.class)) {
						method.invoke(newInstance, rs.getInt(i));
					} else if (type.isAssignableFrom(Boolean.class) || type.isAssignableFrom(boolean.class)) {
						method.invoke(newInstance, rs.getBoolean(i));
					} else if (type.isAssignableFrom(Date.class)) {
						method.invoke(newInstance, rs.getDate(i));
					} else if (type.isAssignableFrom(BigDecimal.class)) {
						method.invoke(newInstance, rs.getBigDecimal(i));
					}
				}
				arrayList.add(newInstance);
			}
			return arrayList;
		} catch (Exception e) {
			logger.error(e);
			throw new FrameException("内部错误,请与管理员联系,对象赋值错误");
		}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值