Reflection (transformar um resultset em list)

bom dia a todos…
imaginem o problema
todos trabalhamos com varias tabelas e cada uma delas utilizamos o resultset
e ha em alguns casos que precisamos gerar em um dao um list de uma tabela
exemplo uma classe Usuario
tenho um resultset da tabela usuario e quero ter um list
para isso eu desenvolvi uma classe que recebe um resultset e transforma em um list de object
vou disponibilizar isso para vcs…

se alguem quiser melhorar ela ou me dar uma ideia melhor por favor
anotem as melhorias aqui para que eu tambem possa melhorar…
obrigado desde ja…

para chamar e ter um retorno com o List
basta fazer o seguinte:

[code]TransfRsEmList trs = new TransRsEmList();
List list = trs.Transf(resultset,NomeDaClasse.class);

for (Object obj : list) {
NomeDaClasse u = (NomeDaClasse) obj;
System.out.println(NomeDaClasse.getCampo());
}[/code]

[code]/*

  • To change this template, choose Tools | Templates
  • and open the template in the editor.
    */
    package tabelas;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
*

  • @author Jonas
    */
    public class TransfRsEmList {

    public List Transf(ResultSet rset, Class c)
    throws SQLException, IllegalAccessException, NoSuchMethodException,
    IllegalArgumentException, InvocationTargetException,
    InstantiationException {

     List<Object> list = new ArrayList<Object>();
    
    
     while (rset.next()) {
         Object obj = c.newInstance();
         for (Method m : c.getMethods()) {
             if (m.getName().substring(0, 3).equals("set")) {
                 Class[] args1 = new Class[1];
                 Class pvec[] = m.getParameterTypes();
                 String s = m.getName().substring(3, m.getName().length());
    
                 if (pvec[0].getName().equals("java.lang.String")) {
                     args1[0] = String.class;
                     obj.getClass().getMethod(m.getName(), args1).invoke(obj, rset.getString(s));
                 }
    
                 if (pvec[0].getName().equals("int")) {
                     args1[0] = int.class;
                     obj.getClass().getMethod(m.getName(), args1).invoke(obj, rset.getInt(s));
                 }
             }
         }
         list.add(obj);
     }
     return list;
    

    }
    }[/code]