【发布时间】:2015-11-26 14:02:34
【问题描述】:
嗨,Spring 中有一个通用类,我想为注入的 bean 获取通用 T 类型类。我知道classic way in Java 并阅读how Spring 4 implements Java Generics。另外,我尝试使用ResolvableType 找到解决方案,但没有任何效果。
@Autowired
GenericDao<SpecificClass> specificdao;
public GenericDaoImpl <T> {
private Class<T> type;
public DaoImpl () {
this.type = ...?
}
public T findById(Serializable id) {
return (T) HibernateUtil.findById(type, id);
}
}
有没有办法避免这种情况?
@Autowired
@Qualifier
GenericDao<SpecificClass> specificdao;
@Repository("specificdao")
public SpecificDaoImpl extends GenericDao<SpecificClass> {
public SpecificDaoImpl () {
// assuming the constructor is implemented in GenericDao
super(this.getClass())
}
}
谢谢。
【问题讨论】:
-
我可能是错的,但我怀疑这是否可以轻松完成(由于类型擦除)。顺便说一句:从您提供的代码来看,您似乎正在尝试重新实现 Spring Data 提供的功能。为什么不使用它呢?
-
是的,但我会自己做。谢谢。
-
一个小注释:如果从超类
GenericDaoImpl调用,结果this.getClass()将是相同的,因为getClass()返回运行时类型。所以类对象不需要是GenericDaoImpl构造函数的参数,GenericDaoImpl可以自己调用。 -
另外:你不需要
findById中的未经检查的强制转换,因为你有类对象。你可以使用return this.type.cast(HibernateUtil.findById(type, id));,它更安全一点,因为它实际上会检查结果是否是正确的类型。 -
This answer 似乎包含几乎相同的信息。