Good night members of the forum! Interested in this question: How to pass a class through a variable or generic? Well, something like createCriteria (var.class) ...

public List<T> readAll() { Session session = null; List<T> obj = null; try{ session = HibernateUtil.getSessionFactory().openSession(); obj = session.createCriteria(T.class).list(); }catch (Exception e){ e.printStackTrace(); }finally { if(session != null && session.isOpen()) session.close(); } return obj; } 

Always in the field of generic T. class the error "Unknown class type" appears. Maybe there is an alternative? Thanks in advance!

    2 answers 2

    The most beautiful solution, in my opinion, is the following:

    Create a base class for the DAO from which all other classes will inherit. In it define the necessary methods. It should be something like this:

     public class GeneralDAO<T>{ public List<T> readAll(){ .... } } public class CatDAO extends GeneralDAO<Cat>{} 

    Now, to obtain an instance of the Class<T>type , in the GeneralDAO<T> class it is necessary to define the constructor as follows:

      private final Class<T> type; public GenericHibernateDAO() { this.persistentClass = (Class<T>) ((ParameterizedType) getClass() .getGenericSuperclass()).getActualTypeArguments()[0]; } 

    More detailed example

    • Yes indeed. I will completely redo the architecture. In the process, it became clear that there will be many entities and writing DAOIml for each one is not an option. Many thanks for the article! - Zelenskiy Ilya

    Try this by passing the class as a method argument. That way you want, it seems, just can not, because see link above:

     public List<T> readAll(Class<T> type) { Session session = null; List<T> obj = null; try{ session = HibernateUtil.getSessionFactory().openSession(); obj = session.createCriteria(type).list(); }catch (Exception e){ e.printStackTrace(); }finally { if(session != null && session.isOpen()) session.close(); } return obj; } 
    • Thank. Everything is working. - Zelenskiy Ilya