我已经写了下节课(清理了一点)
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()
这显然不应该编译——因为当“扩展”或“擦除”时“不”应该有这样的静态方法。Eclipse IDE提供以下编译消息:
无法对
中的非静态方法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();
}
谢谢!