/*
* 定义一个泛型的类
* 这个类的功能主要是
* 把数据库查出来的实体动态的赋给实体。并返回他的结果集
* 只要把目标对象,和数据结果集传给getEntity()就可以。
*/
public class GetEntityBean<T> {
/*
* ZIDUAN 主要是用来检索该实体中的Set 方法
*/
public final static String ZIDUAN = "set";
/*
* 这个方法就是把结果集赋给实体 然后返回一个List【很牛】
*/
public List<T> getEntity(T t, ResultSet re) throws SQLException {
List<T> list = new ArrayList<T>();
Method[] me = t.getClass().getMethods();// 得到该实体的中的所有方法
Class prtype = null;
/*
* 循环结果集把值赋给实体
*/
while (re.next()) {
/*
* 遍历这个类中的所有方法同时给set方法赋值
*/
T t1=null;
try {
// 在用这个方法的时候要注意要明白是怎么回事 重点
t1=(T) t.getClass().newInstance();
} catch (InstantiationException e1) {
e1.printStackTrace();
} catch (IllegalAccessException e1) {
e1.printStackTrace();
}
for (Method md : me) {
String methodName = md.getName();
if (!(methodName.substring(0, 3).equals(ZIDUAN))) {
continue;
}
try {
/*
* 这个主要把实体中的字段和数据库中的字段对应住
*/
String columnName = methodName.substring(3, 4)
.toLowerCase()
+ methodName.substring(4);
/*
* 这个就是赋值的方法
*/
try {
prtype = t.getClass()
.getMethod("get" + methodName.substring(3),
new Class[] {}).getReturnType();
} catch (SecurityException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
if (prtype.toString().equals("int")) {
md.invoke(t1, Integer.parseInt(re.getObject(columnName)
.toString()));
} else {
md.invoke(t1, re.getObject(columnName).toString());
}
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
list.add(t1);
}
return list;
}
}