-1

I'm about to generate an abstract class for DAOs, so I'm just wandering if it is possible to access generic type at runtime in method with signature public Collection<ENTITY> search().

Please, this is the class :

/**
 *
 * @author Upgrade <Salathiel Genese, Yimga Yimga at salathielgenese@gmail.com>
 * @param <ENTITY>
 */
public class DAO<ENTITY extends Entity>
        implements DAOAware<ENTITY>
{

    @Override
    public void delete(ENTITY entity)
    {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public ENTITY save(ENTITY entity)
    {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public ENTITY search(Long id)
    {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public Collection<ENTITY> search()
    {
        return this.getSession().createCriteria(ENTITY.class).list(); // How to retrieve the runtime class of ENTITY
    }

    protected Session getSession()
    {
        return this.sessionFactory.getCurrentSession();
    }

    @Autowired
    private SessionFactory sessionFactory;

}
Salathiel Genese
  • 1,639
  • 2
  • 21
  • 37

1 Answers1

0

Just to point out the obvious, if you have any type returned by this DAO, you can just call getClass() on it.

Class<?> type = dao.search( 1 ).getClass();

But this assumes you have an object or an ID you know will resolve to an object.

markspace
  • 10,621
  • 3
  • 25
  • 39
  • This will nottt let me know the rutime generic type, let say `Person implements Entity`, but output `java.util.Collection` – Salathiel Genese Jun 02 '15 at 17:49
  • In you example code you showed that `search(int)` returns an ENTITY. `search()` (with no arguments) returns a Collection. – markspace Jun 02 '15 at 18:19