论坛首页 入门技术论坛

反射机制实现通用行映射器

浏览 1417 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2009-09-21  
package com.yunchow.util;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.sql.ResultSet;
import java.sql.SQLException;

public class GenericRowMapper<T> implements RowMapper<T> {
	
	/** 要映射的实体对象 */
	protected Class<T> entityClass;
	
	public GenericRowMapper(Class<T> clazz) {
		this.entityClass = clazz;
		System.out.println(clazz.getName());
	}
	
	public T mapperRow(ResultSet rs) throws SQLException {
		T rtn = null;
		try {
			rtn = (T) entityClass.newInstance();
			for (Field field : rtn.getClass().getDeclaredFields()) {
				// System.out.println(field.getType());
				// System.out.println(field.getName());
				String name = field.getName();
				String firstLetter = name.substring(0, 1).toUpperCase();
				String setterName = "set" + firstLetter + name.substring(1);
				Method setter = rtn.getClass().getMethod(setterName,
						new Class[] { field.getType() });
				if (setter != null) {
					// System.out.println("getObject -> " + rs.getObject(name));
					setter.invoke(rtn, rs.getObject(name));
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return rtn;
	}

}
论坛首页 入门技术版

跳转论坛:
Global site tag (gtag.js) - Google Analytics