Java Spring 4泛型类,获取参数化类型

Java Spring 4泛型类,获取参数化类型,java,spring,generics,Java,Spring,Generics,大家好,Spring中有一个泛型类,我想为注入的bean获取泛型T类型类。我知道这本书,也会读书。此外,我还尝试使用查找解决方案,但没有任何效果 @Autowired GenericDao<SpecificClass> specificdao; @Autowired 一般道、特殊道; public GenericDaoImpl{ 私人阶级类型; 公共DaoImpl(){ this.type=。。。? } 公共T findById(可序列化id){ 返回(T)HibernateU

大家好,Spring中有一个泛型类,我想为注入的bean获取泛型T类型类。我知道这本书,也会读书。此外,我还尝试使用查找解决方案,但没有任何效果

@Autowired
GenericDao<SpecificClass> specificdao;
@Autowired
一般道、特殊道;

public GenericDaoImpl{
私人阶级类型;
公共DaoImpl(){
this.type=。。。?
}
公共T findById(可序列化id){
返回(T)HibernateUtil.findById(类型,id);
}
}
有没有办法避免这种情况

@Autowired
@Qualifier
GenericDao<SpecificClass> specificdao;
@Autowired
@限定词
一般道、特殊道;

@Repository(“specificdao”)
公共特定DAOImpl扩展了GenericDao{
公共特定DAOImpl(){
//假设构造函数是在GenericDao中实现的
super(this.getClass())
}
}

谢谢。

如果我理解你的问题:你想要实现的目标非常棘手

您可以使用,然后执行以下操作:

import net.jodah.typetools.TypeResolver;

public GenericDaoImpl <T> {

    private Class<T> type;

    public GenericDaoImpl () { 
         Class<?>[] typeArguments = TypeResolver.resolveRawArguments(GenericDaoImpl.class, getClass());
         this.type = (Class<T>) typeArguments[0];
    }

    public T findById(Serializable id) {
        return (T) HibernateUtil.findById(type, id);
    }
}
为什么??因为每个DAO几乎总是有完全不同于其他DAO的方法。所有人共有的唯一通用方法可能是:
findById
findAll
保存
计数
删除

因此,从GenericDAO子类化是最明显的方式,因为它允许您在具体的DAO中添加任何需要的方法


顺便说一句:您说过希望自己重新实现Spring数据功能。但请注意,在SpringWay中,您仍然需要创建具体的存储库。

我可能错了,但我怀疑这是否容易做到(由于类型擦除)。顺便说一句:从您提供的代码来看,似乎您正在尝试重新实现Spring数据提供的功能。为什么不改用它呢?是的,但我想自己做。谢谢。请注意:如果从超类调用
GenericDaoImpl
,则结果将是相同的,因为
getClass()
返回运行时类型。因此,class对象不需要是
GenericDaoImpl
构造函数的参数,
GenericDaoImpl
可以调用它自己。另外:您不需要未选中的强制转换
findById
,因为您有class对象。您可以使用
返回这个.type.cast(HibernateUtil.findById(type,id))
,这更安全一些,因为它实际上会检查结果的类型是否正确。似乎包含了几乎相同的信息。
@Repository("specificdao")
public SpecificDaoImpl extends GenericDao<SpecificClass> {
      public SpecificDaoImpl () {
          // assuming the constructor is implemented in GenericDao
          super(this.getClass())
      }
}
import net.jodah.typetools.TypeResolver;

public GenericDaoImpl <T> {

    private Class<T> type;

    public GenericDaoImpl () { 
         Class<?>[] typeArguments = TypeResolver.resolveRawArguments(GenericDaoImpl.class, getClass());
         this.type = (Class<T>) typeArguments[0];
    }

    public T findById(Serializable id) {
        return (T) HibernateUtil.findById(type, id);
    }
}
@Autowired
GenericDao<SpecificClass> specificDao;
@Autowired
SpecificDao specificDao;