I need to write java generic method that gets no parameter and returns a List.
This generic method is used hibernate:
public <T> List list() {
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
List result = session.createQuery("from " + T.class.getName()).list();
return result;
}
I am tring to invoke this method. I tried the following but it creates compilation errors:
mgr.list<User>();
mgr.list()<User>;
mgr.list(<User>);
How can I call this method?
I believe what you’re trying to accomplish requires some refactoring. It looks like you’re trying to create a generic Dao class that you can reuse to query any Model object. The problem is that without passing the class to the method, you can’t get the type of the
<T>generic at runtime.One way to accomplish what you want is to create a base dao, which is extended by specific implementations that know the class they’re dealing with at compile time.
Then extend the class:
Then call the method: