In searching for an answer to an interesting situation which I had recently encountered I came upon the following question: Type safety, Java generics and querying
I have written the following class (cleaned up a bit)
public abstract class BaseDaoImpl<T extends Serializable> extends HibernateDaoSupport implements BaseDao<T> {
/**
* Finds and Returns a list of persistent objects by a collection of criterions
* @param criterions
* @return list of persistent objects
* @throws DBException
*/
@SuppressWarnings("unchecked")
protected List<T> findByCriteria(Collection<Criterion> criterions) throws DBException {
try {
DetachedCriteria criteria = DetachedCriteria.forClass(T.class); // BAD!!!
for (Criterion criterion : criterions) {
criteria.add(criterion);
}
List<T> result = getHibernateTemplate().findByCriteria(criteria);
return result;
}
catch (Exception e) {
throw new DBException(T.class + " lookup by " + criterions + " failed", e); // BAD!!!
}
}
}
For some (probably good reason) T.class
causes a compile time error.
My first question is why?
If I change it to T.getClass()
which obviously shouldn't compile - because no 'T' when "expanded" or goes through "erasure" - should have a static method such as that. The eclipse IDE gives the following compilation message:
Cannot make a static reference to the non-static method getClass() from the type Object
My second question is why? And what does this error imply actually?
Finally, would solving this in the manner specified in the link above (or rather my interpretation of) be the most optimal way?
public abstract class BaseDaoImpl<T extends Serializable> extends HibernateDaoSupport implements BaseDao<T>, MyGenericHelper<T> {
/**
* Finds and Returns a list of persistent objects by a collection of criterions
* @param criterions
* @return list of persistent objects
* @throws DBException
*/
@SuppressWarnings("unchecked")
protected List<T> findByCriteria(Collection<MyCriterion> criterions) throws DBException {
try {
DetachedCriteria criteria = DetachedCriteria.forClass(getGenericClass()); // BAD!!!
for (Criterion criterion : criterions) {
criteria.add(criterion);
}
List<T> result = getHibernateTemplate().findByCriteria(criteria);
return result;
}
catch (Exception e) {
throw new DBException(getGenericClass() + " lookup by " + criterions + " failed", e); // BAD!!!
}
}
}
public interface MyGenericHelper<T extends Serializable> {
public Class<T> getGenericClass();
}
Thanks!