摸鱼一天,通过反射泛型写了个封装Bean的工具类
开始的开始
今天公司安排了个小任务,通过jdbc查询数据库,然后打印出来。我心里一想,不是很简单吗,然后就着手开始做了,确实很简单,增删改查用不了多久
但是每当查完数据后发现,每次我查完数据都要遍历结果集然后通过对象set方法进行注入值,就觉得很烦,也不想用以前用的工具类像BeanUtils
脑子里就想能不能手写一个结果集工具类来封装Bean,还真可以,怼一天怼出来,不辜负我摸鱼的时光。
思路:
- 给一个静态方法传入结果集,还有 类名.class就能进行自动封装并返回bean对象。
- 通过class对象newInstance()实例化为返回对象result。
- 接着通过class对象获取该对象属性数组(包含所有属性)
- 对属性数组进行遍历,getFiledName()获取属性名就可以确定方法名了name->setName()
- 根据属性获取对应的type
- 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;
}