想写个通用的方法封装JDBC的ResultSet,返回一个特定类的ArrayList,比如有个学生类Student,调用形式(省略了Connection和表名):
ArrayList<Student> = meth();
或者
methd(ArrayList<Student>);
主要的思路是方法里通过反射赋值给对象,然后add到ArrayList里,不过方法定义时只能使用Object等通用的类型或者通配符,
所以方法里怎么获得对象并反射解析,再add到ArrayList里是个问题,有没有人给点思路?
------解决思路----------------------
public <T> List<T> meth(Class<T> cls)
{
ArrayList<T> rc=new ArrayList<T>();
try
{
//for()
//{
T obj=cls.newInstance();
//do xxxx
rc.add(obj);
//}
}
catch(Exception e){e.printStackTrace();}
return rc;
}
List<Student> datas=meth(Student.class);