java—在运行时自动连接时获取泛型类类型

a11xaf1n  于 2021-07-24  发布在  Java
关注(0)|答案(0)|浏览(219)

我有一个基类,它在第三方库和特定的repo类上运行。我使用基类作为构图。在将泛型类型作为运行时时自动连接基类时出错。

@Repository
public interface BaseRepo<T, K> { 
  public void save(T obj);
  public T get(K id);

}

@Repository
public class BaseRepoImpl<T, K> implements BaseRepo<T, K>{ 

  private Class<T> classType;

  public BaseRepoImpl(){
    Type[] types = ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments();
   this.classType = types[0];
  }

  public void save(T obj){
    somethirdParty.save(obj);
  }

  public T get(K id){
     return somethirdParty.get(classType, id);
   }
}

@Repository
public interface MyRepo { 
  public void save(MyObject obj);
  public T get(String id);

}

@Repository
public class MyRepoImpl implements MyRepo{ 

   private BaseRepo<MyClass, String> baseRepo;

   public void save(T obj){
     baseRepo.save()
   }

  public T get(String id){
    return baseRepo.get(id);
  }
}

启动tomcat时出现以下错误-

main ContextLoader Context initialization failed org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'baseRepoImpl' defined in file [...BaseRepoImpl.class]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.intuit.qbo.data.dynamodb.DynamoDBRepositoryImpl]: Constructor threw exception; nested exception is java.lang.ClassCastException: class java.lang.Class cannot be cast to class java.lang.reflect.ParameterizedType (java.lang.Class and java.lang.reflect.ParameterizedType are in module java.base of loader 'bootstrap')
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:1303)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1197)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:555)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:515)
    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:320)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:318)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199)

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题