当前位置: 代码迷 >> J2EE >> ArrayList的泛型有关问题
  详细解决方案

ArrayList的泛型有关问题

热度:23   发布时间:2016-04-17 23:01:35.0
ArrayList的泛型问题
想写个通用的方法封装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);
  相关解决方案