标签:
基本类:
@Repository public class HibernateDao<T, PK extends Serializable>{ protected Logger logger = LoggerFactory.getLogger(getClass()); protected Class<T> entityClass; public HibernateDao() { logger.debug(String.valueOf(getEntityClass())); } /** * 求泛型的类类型 * @return */ protected Class<T> getEntityClass(){ logger.debug("this.class: " + this.getClass()); logger.debug("this.getClass().getGenericSuperclass(): " + this.getClass().getGenericSuperclass()); if(null == entityClass){ entityClass = (Class<T>) ((ParameterizedType) this.getClass().getGenericSuperclass()).getActualTypeArguments()[0]; } logger.debug("entityClass: " + entityClass); return entityClass; } .... }
@Repository public class BaseDao<T, PK extends Serializable> extends HibernateDao<T,String> { }
//应用层 处理具体的业务 @Repository public class UserDao extends BaseDao<User, String> { }
继承关系很明显了,我现在BaseSrvice中实例化BaseDao:
@Service @Transactional public abstract class BaseService<T, PK extends Serializable> { protected Logger logger = LoggerFactory.getLogger(this.getClass()); @Autowired private BaseDao baseDao; public BaseService() { printEntityClass(); } //帮助理解 private void printEntityClass(){ ParameterizedType type = (ParameterizedType) this.getClass().getGenericSuperclass(); Class c = (Class) type.getActualTypeArguments()[0]; logger.debug(c.toString()); } ... }
之后我在Junit中编写一个测试类【注意:应用层的测试实例】:
public class UserServiceTest extends BaseTestConfig { @Autowired private UserService userService; @Test public void testList2(){ String id = "40283a814f7d92f7014f7d956bf50007"; userService.get(id); } }
运行结果
说明HibernateDao求泛型的时候,抛异常了。
修改下BaseService,将
@Autowired private BaseDao baseDao;
改为
@Autowired private BaseDao<T,String> baseDao;
再次运行:
异常消失,注意:HibernateDao求泛型的打印输出的变化。
II.this.getClass().getGenericSuperclass();求出的是直接父类。如UserDao的直接父类为BaseDao而不是HibernateDao。
标签:
原文地址:http://www.cnblogs.com/licqs/p/4821398.html