简体   繁体   中英

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.

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 (eg T t = nomClass.newInstance(); ), you'll need to throw or handle IllegalAccessException and InstantiationException

You could use the same generic parameterized type in the parameter type and the type object returned :

   public <T> List<T> listerUser( Class<T> nomClass ) throws GestionExceptionsDAO 

After you can call it like that:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM