Issue
i have a generic dao class and i'm trying to use spring dependency injection but i have the following error
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'BaseDao' defined in ServletContext resource [/WEB-INF/applicationContext.xml]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [com.abgc.fab.dao.BaseDao]: Constructor threw exception; nested exception is java.lang.ClassCastException: sun.reflect.generics.reflectiveObjects.TypeVariableImpl cannot be cast to java.lang.Class
my applicationContext.xml file
<bean id="BaseDao" class="com.abgc.fab.dao.BaseDao">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
my basedao class :
public class BaseDao<TEntity> extends CommonDao<TEntity> implements IBaseDao<TEntity> {
}
public abstract class CommonDao<TEntity> extends FabObject implements ICommonDao<TEntity> {
public CommonDao() {
Type t = getClass().getGenericSuperclass();
ParameterizedType pt = (ParameterizedType) t;
this.classEntity = (Class<TEntity>) pt.getActualTypeArguments()[0];
}
any help please ?
Solution
Having a deep hierarchy you'll need to use something like TypeTools (which I authored):
class DeviceDao extends BaseDao<Device> {}
Class<?> entityType = TypeResolver.resolveRawArgument(IBaseDao.clas, DeviceDao.class);
assert entityType == Device.class;
Note: As always, type arguments can only be resolved at runtime if they're captured in a type definition. So subclassing BaseDao
is necessary.
Answered By - Jonathan
Answer Checked By - David Goodson (JavaFixing Volunteer)