摸鱼一天,通过反射泛型写了个封装Bean的工具类

摸鱼一天,通过反射泛型写了个封装Bean的工具类

开始的开始

今天公司安排了个小任务,通过jdbc查询数据库,然后打印出来。我心里一想,不是很简单吗,然后就着手开始做了,确实很简单,增删改查用不了多久

但是每当查完数据后发现,每次我查完数据都要遍历结果集然后通过对象set方法进行注入值,就觉得很烦,也不想用以前用的工具类像BeanUtils

脑子里就想能不能手写一个结果集工具类来封装Bean,还真可以,怼一天怼出来,不辜负我摸鱼的时光。

思路:

  1. 给一个静态方法传入结果集,还有 类名.class就能进行自动封装并返回bean对象。
  2. 通过class对象newInstance()实例化为返回对象result。
  3. 接着通过class对象获取该对象属性数组(包含所有属性)
  4. 对属性数组进行遍历,getFiledName()获取属性名就可以确定方法名了name->setName()
  5. 根据属性获取对应的type
  6. if判断类型进行调用invoke进行属性注入。

代码如下:

//根据类名将查询结果resultSet封装成对象
//数据库查出来的数据字段必须跟对象属性一致
public static <T>T resultToModel(ResultSet rs, Class<T> t) {
    T result = null;//封装数据完返回的Bean对象
    try {
        result = t.newInstance();//返回的对象
        //根据class获取到对应的字段数组
        Field[] fields = t.getDeclaredFields();
        for (int i = 0; i < fields.length; i++) {
            Field field = fields[i];
            //获取字段的名字
            String fieldName = field.getName();
            //用字段名得出set方法,set+将首字母大写(参考网上做法)
            String setMethodName = "set" + fieldName.substring(0, 1).toUpperCase() + 				fieldName.substring(1);

            //获取字段类型
            String type = field.getType().toString();
            //2.通过调用set方法进行注入
            if (type.equals("class java.lang.String")) {
                //类型匹配 则获取注入方法
                Method method = t.getMethod(setMethodName, String.class);
                method.invoke(result, rs.getString(fieldName));
            } else if (type.equals("int")) {
                Method method = t.getMethod(setMethodName, int.class);
                method.invoke(result, rs.getInt(fieldName));
            } else if (type.equals("class java.util.Date")) {
                Method method = t.getMethod(setMethodName, java.util.Date.class);
                method.invoke(result, rs.getDate(fieldName));
            } else {
                throw new RuntimeException("类型出现异常");
            }
        }
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    } catch (NoSuchMethodException e) {
        e.printStackTrace();
    } catch (InvocationTargetException e) {
        e.printStackTrace();
    } catch (InstantiationException e) {
        e.printStackTrace();
    } catch (SQLException e) {
        e.printStackTrace();
    }
    //3.返回该对象
    System.out.println("当前对象属性注入成功:"+ result);
    return result;
}
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值