我尝试做Generic Dao类实现。但我坚持这样的错误 -
"sun.reflect.generics.reflectiveObjects.TypeVariableImpl cannot be cast to java.lang.Class"
我的通用类名访问方法代码是,
protected Class<T> getEntityClass() {
if (entityClass == null) {
entityClass = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
}
return entityClass;
}
我不明白这个问题。请帮帮我。
修改
界面 -
import java.util.List;
public interface IGenericDao<T> {
void update(T entity);
T merge(T entity);
int save(T entity);
void delete(T entity);
T find(int id);
List<T> findAll(int PageNo) throws Exception;
List<T> find();
void saveOrUpdate(T entity);
}
类,
public class Services<T> extends IGenericDaoImpl<T> {
}
抽象类 -
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;
import javax.transaction.Transactional;
import org.hibernate.Criteria;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
@SuppressWarnings("unchecked")
@Transactional
public abstract class IGenericDaoImpl<T> implements IGenericDao<T> {
private Class<T> entityClass;
@Autowired
private SessionFactory sessionFactory;
protected Class<T> getEntityClass() {
if (entityClass == null) {
entityClass = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
//entityClass=(Class<T>) GenericTypeResolver.resolveTypeArgument(getClass(), IGenericDaoImpl.class);
}
return entityClass;
}
public void update(T entity) {
sessionFactory.getCurrentSession().update(entity);
}
public T merge(T entity) {
return (T) sessionFactory.getCurrentSession().merge(entity);
}
public int save(T entity) {
return (Integer) sessionFactory.getCurrentSession().save(entity);
}
public void delete(T entity) {
sessionFactory.getCurrentSession().delete(entity);
}
public T find(int id) {
return (T) sessionFactory.getCurrentSession().get(getEntityClass(), id);
}
public List<T> find() {
return sessionFactory.getCurrentSession().createQuery("from " + getEntityClass().getName()).list();
}
public void saveOrUpdate(T entity) {
sessionFactory.getCurrentSession().saveOrUpdate(entity);
}
public List<T> findAll(int PageNo) throws Exception {
System.out.println("::::"+getEntityClass());
int maxresult=5;
Criteria criteria = sessionFactory.getCurrentSession().createCriteria(getEntityClass())
.setFirstResult((PageNo-1)*maxresult)
.setMaxResults(maxresult);
//System.out.println("Criteria: "+criteria.setProjection(Projections.rowCount()));
return criteria.list();
}
}