前段时间写一个RSS聚合系统,需要大量用到从数据库中将表中符合条件的记录取出来生成相应的javabean的集合,于是结合泛型和反射机制写了一个较通用的封装类。源代码如下:
java 代码
- /**
- * 根据传入的javabean对象和ResultSet产生一个具体javaBean的Collection
- */
- import java.util.*;
- import java.sql.*;
- import java.lang.reflect.*;
- public class BeanCollectionBuilder{
- private BeanCollectionBuilder(){}
- /**
- * 得到一个jvaBean的Colleciton
- * @param bean 要生成的javaBean
- * @param rs 记录集
- * @return 一个具体javaBean的Collection
- */
- public static <T> Collection<T> getBeanCollection(T object,ResultSet rs){
- Collection<T> collection = null;
- Class bean = object.getClass();
- Method[] methods = bean.getMethods();//获得bean的方法
- List<Method> setMethodList = new ArrayList<Method>();//构造一个List用来存放bean中所有set开头的方法
- //获得Bean中所有set方法
- for (int i = 0;i < methods.length;i++){
- Method method = methods[i];
- if (method.getName().startsWith("set")){
- setMethodList.add(method);
- }
- }
- ResultSetMetaData meta = null;
- try{
- meta = rs.getMetaData();
- //如果记录集中的字段不等于Bean中的属性值,抛出异常
- if (setMethodList.size() != meta.getColumnCount()){
- throw new IllegalArgumentException("传入的JavaBean与ResultSet不一致");
- }
- //将得到的set方法构建一个Method Array
- Method[] setMethodArray = new Method[setMethodList.size()];
- setMethodList.toArray(setMethodArray);
- int count = setMethodArray.length;
- //构建一个String数组用来存放对应的ResultSet中的字段
- String[] field = new String[count];
- for (int i = 0;i < count;i++){
- field[i] = setMethodArray[i].getName().substring(3).toLowerCase();
- }
- //将ResultSet中的每一条记录构建一个JavaBean实例,然后添加到Collection中
- collection = new ArrayList<T>();
- while(rs.next()){
- T o = (T)bean.newInstance();
- for (int i = 0;i < count;i++){
- Object[] param = new Object[]{rs.getObject(field[i])};
- setMethodArray[i].invoke(o,param);
- }
- collection.add(o);
- }
- }
- catch(Exception e){
- throw e;
- }
- finally{
- return collection;//最后返回这个Collection
- }
- }
- }