---
title: "使用反射封装RowMapper"
author: "ldz0414"
date: "2013-08-13T15:16:41Z"
tags: []
categories: ["编程语言"]
slug: "rowmapper"
draft: false
lastmod: "2013-09-29T16:21:40Z"
id: 1923994
url: "https://0414.iteye.com/blog/1923994"
---

\[code="java"] package com.xinhuanet.cloudDesk.dao.impl; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.sql.ResultSet; import java.sql.SQLException; import org.apache.log4j.Logger; import org.springframework.jdbc.core.RowMapper; public abstract class BaseRowMapper implements RowMapper { private static final Logger log = Logger.getLogger(BaseRowMapper.class); @Override public T mapRow(ResultSet rs, int index) throws SQLException { try { Class clazz = Class.forName(this.getClassName()); Object obj = clazz.newInstance(); for (Class clazztemp = clazz; clazztemp != Object.class; clazztemp = clazztemp .getSuperclass()) { Field\[] fields = clazztemp.getDeclaredFields(); if (fields == null) { return null; } for (int i = 0; i &lt; fields.length; i++) { String fieldName = fields\[i].getName(); Class fieldClass = fields\[i].getType(); String methodName = "set" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1); Method method = clazztemp.getDeclaredMethod(methodName, new Class\[] { fieldClass }); Object param = null; try { param = rs.getObject(fieldName.toLowerCase()); if(param != null) { method.invoke(obj, param); } } catch (Exception e) { log.error("fieldName:" + fieldName + "是" + fieldClass + "目标参数是：" + param.getClass()); log.error(e); } } } return (T) obj; } catch (Exception e) { log.error(e); e.printStackTrace(); return null; } } /\** * 子类的类名 * * @return \*/ public abstract String getClassName(); } \[/code]