akuma8 akuma8 - 15 days ago 5
Java Question

Using a generic class as a type of java List

I would like to create the methode below :

@Override
public List<?> listerUser( Class<?> nomClass ) throws GestionExceptionsDAO {

Object tableSQL;

try {
tableSQL = nomClass.newInstance();
} catch ( InstantiationException e1 ) {
e1.printStackTrace();
} catch ( IllegalAccessException e1 ) {
e1.printStackTrace();
}

List<tableSQL> listeUser;//Error : tableSQL cannot be resolved to a type

Session session = sessionFactory.openSession();
session.beginTransaction();
Query requete = session.createQuery( REQUETE_LIST );
requete.setParameter( REQUETE_LIST, tableSQL );

try {
listeUser = (List<tableSQL>) requete.getResultList();
} catch ( NoResultException e ) {
throw null;
} catch ( Exception e ) {
throw new GestionExceptionsDAO( e );
} finally {
session.close();
}
return listeUser;
}


What I try to do is to create a method which takes in parameter a class name, and returns a list of objects of that class. I think it's simple but I am finding some difficulties to do it. Many thanks.

Answer

You cannot use a reference to an instance variable to parametrize a generic type.

The idiom you are probably looking for is the one for a generic method, that returns a List parametrized with the type of the given Class argument:

public <T>List<T> listerUser(Class<T> nomClass) {
    List<T> result = new ArrayList<>();
    // TODO populate the result based on your query 
    return result;
}

You can also bind T to children or parent of a given class / interface (inclusive upper/lower bounds) by using the extends or super keywords.

For instance, given a definition of:

public <T extends CharSequence>List<T> listerUser( Class<T> nomClass )

The invocation could be:

List<String> list = listerUser(String.class);

Notes

  • Docs on generic methods here.
  • If you plan on using reflection to initialize a new instance of T (e.g. T t = nomClass.newInstance();), you'll need to throw or handle IllegalAccessException and InstantiationException