今天主要来复习一下java的反射技术,利用反射和泛型设计了一个同类来操作数据访问层
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.sql.SQLException;
import java.util.List;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
//定义一个带有泛型的base类
public class BaseDao<T> {
private Class clazz; //得到的类名称
private String tableName; //需要操作的表的名字
public BaseDao(){
Type p = this.getClass().getGenericSuperclass(); //得到运行的类的带有泛型的父类
ParameterizedType pt = (ParameterizedType) p; //把泛型类变成参数化类型
Type[] types = pt.getActualTypeArguments(); //得到所有的泛型
clazz = (Class) types[0];
tableName = clazz.getSimpleName().toLowerCase(); //规定数据库的表和类名一致
}
QueryRunner qr = new QueryRunner(C3P0Util.getDataSource());
public List<T> findAll(){
try {
return qr.query("select * from "+tableName+"", new BeanListHandler(clazz));
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
throw new RuntimeException(e);
}
}
public T findById(String id){
try {
return (T)qr.query("select * from "+tableName+" where id=?", new BeanHandler(clazz),id);
} catch (SQLException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
}
这个就是主类关于让其他dao来继承的base类,通过泛型的类型传入可以得到相应 的类型,
public class StudentDao extends BaseDao<Student> {
}
这个就能得到Student类
public class AdminDao extends BaseDao<Admin> {
}
然而这个就能得到Admin类
来复习java反射和泛型主要用于学习框架打下一些基础,做一些学习前的预习,接下来就要去学习javaee的小目标,三大框架,struts、hibernate、spring