模仿hibernate封装javabean

2014-11-24 17:05:03 · 作者: · 浏览: 2
package cn.itcast.user.tool;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
/**
 *	jdbc封装类 
 *			clazz : bean类型
 *			result :结果集
 *			arrayList : 用于包装bean类型的数据
 *    实现思路
 *           1: 使用反射获取所有成员变量:getDeclaredFields
 *           2:  以变量名跟字段相同的情况获取result的值
 *           3: 以javabean规则set+大写+变量名,赋值
 *           4:防止方法为private修饰,故加setAccessible(true)取消安全检查
 */
@SuppressWarnings({ "unchecked", "rawtypes" })
public class ClassReflectionTool {
	
	public static void findAll(Class clazz, ResultSet result,List arrayList) {
		try {
			Field[] fields = clazz.getDeclaredFields();
			while(result.next()){
				Object newInstance = clazz.newInstance();
				for (Field f : fields) {
					String fieldName = f.getName();
					Class fieldClass = (Class) f.getGenericType();
					Object objVal = null;
					
					try {
						objVal = result.getObject(fieldName);
						Method method = clazz.getMethod(change(fieldName),fieldClass);
						method.setAccessible(true);//取消检查
						method.invoke(newInstance, objVal);
					} catch (NoSuchMethodException e) {
						System.out.println("找不到set方法\t"+e);
					} catch (SQLException e) {
						System.out.println("字段 与  "+clazz+"中有变量名不匹配"+e);
					}
					
					//System.out.println("字段名:" + f.getName() + "\t  类型为" + fieldType);
				}
				arrayList.add(newInstance);
			}

		} catch (IllegalAccessException e) {
			throw new RuntimeException("初始化..."+clazz+"...失败");
		} catch (InstantiationException e) {
			throw new RuntimeException("初始化..."+clazz+"...失败");
		}  catch (Exception e) {
			throw new RuntimeException(e);
		} 
	}

	private static String change(String fieldName) {
		StringBuilder sb = new StringBuilder("set");
		sb.append(fieldName.substring(0, 1).toUpperCase());
		sb.append(fieldName.substring(1,fieldName.length()));
		return sb.toString();
	}

}