在寻找我最近遇到的有趣情况的答案时,我遇到了以下问题:类型安全,Java泛型和查询
我写了下面的课(清理了一下)
public abstract class BaseDaoImpl extends HibernateDaoSupport implements BaseDao {
/**
* 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 findByCriteria(Collection criterions) throws DBException {
try {
DetachedCriteria criteria = DetachedCriteria.forClass(T.class); // BAD!!!
for (Criterion criterion : criterions) {
criteria.add(criterion);
}
List result = getHibernateTemplate().findByCriteria(criteria);
return result;
}
catch (Exception e) {
throw new DBException(T.class + " lookup by " + criterions + " failed", e); // BAD!!!
}
}
}
对于某些(可能是好的理由)T.class导致编译时错误.
我的第一个问题是为什么?
如果我把它改成T.getClass()显然不应该编译 - 因为没有'T'当"扩展"或经历"擦除" - 应该有一个静态的方法,如那.eclipse IDE提供以下编译消息:
无法从Object类型对非静态方法getClass()进行静态引用
我的第二个问题是为什么?这个错误实际上意味着什么?
最后,以上述链接中指定的方式解决这个问题(或者更确切地说,我的解释)是最优化的方式吗?
public abstract class BaseDaoImpl extends HibernateDaoSupport implements BaseDao, MyGenericHelper {
/**
* 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 findByCriteria(Collection criterions) throws DBException {
try {
DetachedCriteria criteria = DetachedCriteria.forClass(getGenericClass()); // BAD!!!
for (Criterion criterion : criterions) {
criteria.add(criterion);
}
List result = getHibernateTemplate().findByCriteria(criteria);
return result;
}
catch (Exception e) {
throw new DBException(getGenericClass() + " lookup by " + criterions + " failed", e); // BAD!!!
}
}
}
public interface MyGenericHelper {
public Class getGenericClass();
}
谢谢!