测试 DAO 时出错:sun.reflect.generics.reflectiveObjects.TypeVariableImpl 无法转换为 java.lang.Class

Posted

技术标签:

【中文标题】测试 DAO 时出错:sun.reflect.generics.reflectiveObjects.TypeVariableImpl 无法转换为 java.lang.Class【英文标题】:Error testing DAOs: sun.reflect.generics.reflectiveObjects.TypeVariableImpl cannot be cast to java.lang.Class 【发布时间】:2012-02-13 14:54:06 【问题描述】:

我是 Spring + Hibernate 的新手,我正在运行测试以查看我的 DAO 是否正常工作。我收到以下错误,在 Google 中搜索时会产生很多不同的答案(主要是我检查过的拼写错误)。我希望你能帮我解决这个问题:

java.lang.IllegalStateException: Failed to load ApplicationContext
        at org.springframework.test.context.TestContext.getApplicationContext(TestContext.java:308)
        at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:109)
        at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:75)
        at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:321)
        at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:220)
        at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:301)
        at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
        at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:303)
        at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:240)
        at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:49)
        at org.junit.runners.ParentRunner$3.run(ParentRunner.java:193)
        at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:52)
        at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:191)
        at org.junit.runners.ParentRunner.access$000(ParentRunner.java:42)
        at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:184)
        at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
        at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
        at org.junit.runners.ParentRunner.run(ParentRunner.java:236)
        at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:180)
        at org.junit.runner.JUnitCore.run(JUnitCore.java:157)
        at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:71)
        at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:199)
        at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:62)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
        at com.intellij.rt.execution.application.AppMain.main(AppMain.java:120)
    Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'nominationDao' defined in file [C:\IdeaProjects\Projects\branch\dev\test-dataacess\target\classes\com\dev\test\data\dao\hibernate\NominationHibernateDAO.class]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [com.dev.test.data.dao.hibernate.NominationHibernateDAO]: Constructor threw exception; nested exception is java.lang.ClassCastException: sun.reflect.generics.reflectiveObjects.TypeVariableImpl cannot be cast to java.lang.Class
        at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:288)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1003)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:907)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:485)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
        at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:295)
        at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
        at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:292)
        at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
        at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:580)
        at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:900)
        at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:455)
        at org.springframework.test.context.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.java:84)
        at org.springframework.test.context.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.java:1)
        at org.springframework.test.context.TestContext.loadApplicationContext(TestContext.java:280)
        at org.springframework.test.context.TestContext.getApplicationContext(TestContext.java:304)
        ... 27 more
    Caused by: org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [com.dev.test.data.dao.hibernate.NominationHibernateDAO]: Constructor threw exception; nested exception is java.lang.ClassCastException: sun.reflect.generics.reflectiveObjects.TypeVariableImpl cannot be cast to java.lang.Class
        at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:162)
        at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:108)
        at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:280)
        ... 42 more
    Caused by: java.lang.ClassCastException: sun.reflect.generics.reflectiveObjects.TypeVariableImpl cannot be cast to java.lang.Class
        at com.dev.test.data.dao.hibernate.AbstractHibernateDAO.<init>(AbstractHibernateDAO.java:50)
        at com.dev.test.data.dao.hibernate.NominationHibernateDAO.<init>(NominationHibernateDAO.java:36)
        at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
        at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39)
        at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
        at java.lang.reflect.Constructor.newInstance(Constructor.java:513)
        at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:147)
        ... 44 more

什么可能导致这种情况?如果我在 AbstractHibernateDAO 和 NominationHibernateDAO 中进行了编辑,请告诉我。

谢谢!

这里编辑的是sn-ps:

这是 AbstractHibernateDAO 的 sn-p,第 50 行是注释:

public abstract class AbstractHibernateDAO<T, K extends Serializable>
        implements DAO<T, K> 

    protected Logger logger = LoggerFactory.getLogger(this.getClass());

    private SessionFactory sessionFactory;

    private Class<T> persistentClass;

    protected AbstractHibernateDAO(SessionFactory sessionFactory) 
        this.sessionFactory = sessionFactory;
        this.persistentClass = (Class<T>) ((ParameterizedType) //LINE 50
                getClass().getGenericSuperclass()).getActualTypeArguments()[0];
    

第 36 行之后是对 NominationHibernateDAO 的这个 sn-p 的评论:

@Repository("nominationDao")
public class NominationHibernateDAO<T extends Nomination>
        extends AbstractHibernateDAO<T,Integer>
        implements NominationDAO<T> 


      @Autowired(required = true)
      public NominationHibernateDAO(SessionFactory sessionFactory) 
           super(sessionFactory); //LINE 36
      

【问题讨论】:

@hvgotcodes 我在错误指向的地方添加了 sn-ps 您能展示一下您是如何在您的 junit 测试中加载应用程序上下文的吗? 【参考方案1】:

表达式

getClass().getGenericSuperclass()).getActualTypeArguments()[0]

指代替换为AbstractHibernateDAO 的第一个类型参数的值(在AbstractHibernateDAO.java 中用T 表示)。由子类NominationHibernateDAO 替换的类型仍然不具体,它是T extends Nomination,这绝对不是java.lang.Class 实例,而是Type 实例(TypeVariableImplType 的实现。

如果NominationHibernateDAO 是这样声明的:

class NominationHibernateDAO extends AbstractHibernateDAO<Nomination, Integer>  ...

那么AbstractHibernateDAO 构造函数的魔法就会起作用。或者,您可以(或者甚至应该?)实例化 NominationHibernateDAO 的子类,声明如下:

class ConcreteNominationHibernateDAO
        extends NominationHibernateDAO<ConcreteNominationSubclass>  ...

new NominationHibernateDAO<ConcreteNominationSubclass>() 

同样,这不会引发问题。

您确定 NominationHibernateDAO 类是用作 Spring bean 的吗?

【讨论】:

是的,应该。但现在我想我明白你在说什么了......我认为我遇到的问题是我有 3 个不同的实体扩展了提名实体,还有 3 个其他 DAO 从提名 DAO 扩展。我会对此进行调查,但您的答案似乎正是我想要的。谢谢。 只是为了澄清我确实有以下几点:public final class SpecificNominationHibernateDAO extends NominationHibernateDAO&lt;SpecificNomination&gt; implements SpecificNominationDAO 在 3 个不同的独立 DAO 上,这与您所说的类似,但我想我的实现有点错误。 我通过简单地将NominationHibernateDAO 设为抽象类并为通用提名使用新的HibernateDAO bean 来解决此问题,这样我可以舒适地从NominationHibernateDAO 扩展,同时仍保持通用版本.超级简单,但当然有时很难看到发生了什么。非常感谢您的帮助。 @Nimchip 使用泛型&lt;T extends Xxx&gt; 抽象类,不要将其作为bean,将解决问题,它也解决了我的问题。你应该把这个结论作为一个单独的答案或者放在问题本身中,这样更多的人可以清楚地理解它。 可能相关:我在尝试从构造函数检查参数化类型(通过反射)时遇到了这个异常。在构造函数完成后做同样的事情工作正常。

以上是关于测试 DAO 时出错:sun.reflect.generics.reflectiveObjects.TypeVariableImpl 无法转换为 java.lang.Class的主要内容,如果未能解决你的问题,请参考以下文章

GreenDao 生成器类在生成模型和 dao 类时出错。

beans.factory.BeanCreationException:创建名为“dao”的bean时出错:注入持久性依赖项失败

使用 GenericDAO 插入第二个数据源时出错

尝试对 DAO 类进行单元测试时,SessionFactory 没有自动装配

基于MVC实现增删查改

基于MVC实现增删查改