java.lang.ClassCastException : java. lang.Class 无法转换为 java.lang.reflect.ParameterizedType

标签 java spring hibernate

我使用泛型创建了接口(interface)和类的层次结构,但把一切都搞砸了。
最顶层的类是 AbstractJpaEntity,它由所有域实体扩展

@MappedSuperclass
@EntityListeners({AbstractJpaEntity.AbstractEntityListener.class})
@SuppressWarnings("serial")
public class AbstractJpaEntity implements Serializable

ProductTypeDomain 类类似于标记类,用于分离出少数表实体。

@SuppressWarnings("serial")
@MappedSuperclass
@EntityListeners({ ProductTypeDomain.AbstractEntityListener.class })
public class ProductTypeDomain extends AbstractJpaEntity{}

接口(interface)“GenericDao”定义

public interface GenericDao<T> {...

抽象类GenericDaoImpl(该类具有持久化、合并等通用功能)

public abstract class GenericDaoImpl<T extends AbstractJpaEntity> implements GenericDao<T> {...

接口(interface) ProductTypeDao

public interface ProductTypeDao<T extends ProductTypeDomain> extends GenericDao<T> {

Spring 存储库类 ProductTypeDaoImpl

@Repository("productTypeDao")
public class ProductTypeDaoImpl extends GenericDaoImpl implements ProductTypeDao
{....

在 spring 服务类 ProductManagerServiceimpl 中,我正在 Autowiring 存储库 productTypeDao

@Service("productManager")
public class ProductManagerServiceimpl implements ProductManagerService{
    @Autowired
    ProductTypeDao productTypeDao;

在运行代码时,出现以下错误

引起:org.springframework.beans.factory.BeanCreationException:无法 Autowiring 字段:com.jodo.cms.service.ProductManagerService com.jodo.cms.controllers.ProductController.productManager;嵌套异常是 org.springframework.beans.factory.BeanCreationException:创建名称为“productManager”的 bean 时出错: Autowiring 依赖项注入(inject)失败;嵌套异常是 org.springframework.beans.factory.BeanCreationException:无法 Autowiring 字段:com.jodo.cms.dao.ProductTypeDao com.jodo.cms.service.impl.ProductManagerServiceimpl.productTypeDao;嵌套的异常是 org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'productTypeDao' defined in file [/home/jodo/Server/Tomcat/webapps/jodocms/WEB-INF/classes/com/jodo/cms/dao/impl/ProductTypeDaoImpl.class]: bean实例化失败;嵌套异常是 org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [com.jodo.cms.dao.impl.ProductTypeDaoImpl]: Constructor throw exception;嵌套异常是 java.lang.ClassCastException: java.lang.Class cannot be cast to java.lang.reflect.ParameterizedType

Full Stacktrace is
-------------------------------
09:24:29,443  INFO XmlWebApplicationContext:1020 - Closing Root WebApplicationContext: startup date [Tue Apr 15 08:38:10 IST 2014]; root of context hierarchy
09:24:29,445  INFO DefaultListableBeanFactory:433 - Destroying singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@153a859b: defining beans [org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,org.springframework.context.annotation.internalPersistenceAnnotationProcessor,productTypeDao,productEntityDao,productCategoryDao,categoryTreeDao,categoryEntityDao,categoryManager,productManager,dataSource,entityManagerFactory,transactionManager,org.springframework.aop.config.internalAutoProxyCreator,org.springframework.transaction.annotation.AnnotationTransactionAttributeSource#0,org.springframework.transaction.interceptor.TransactionInterceptor#0,org.springframework.transaction.config.internalTransactionAdvisor,log4jInitialization,org.springframework.context.annotation.ConfigurationClassPostProcessor$ImportAwareBeanPostProcessor#0]; root of factory hierarchy
09:24:29,460  INFO LocalContainerEntityManagerFactoryBean:441 - Closing JPA EntityManagerFactory for persistence unit 'default'
09:24:29,461  INFO SessionFactoryImpl:927 - closing
09:24:41,129  INFO DefaultListableBeanFactory:433 - Destroying singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@c27de92: defining beans [productController,categoryController,org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,org.springframework.context.annotation.internalPersistenceAnnotationProcessor,org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping#0,org.springframework.format.support.FormattingConversionServiceFactoryBean#0,org.springframework.validation.beanvalidation.LocalValidatorFactoryBean#0,org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter#0,org.springframework.web.servlet.handler.MappedInterceptor#0,org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver#0,org.springframework.web.servlet.mvc.annotation.ResponseStatusExceptionResolver#0,org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver#0,org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping,org.springframework.web.servlet.mvc.HttpRequestHandlerAdapter,org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter,org.springframework.context.annotation.ConfigurationClassPostProcessor$ImportAwareBeanPostProcessor#0]; parent: org.springframework.beans.factory.support.DefaultListableBeanFactory@5803bbcc
09:24:41,134 ERROR DispatcherServlet:457 - Context initialization failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'productController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: com.jodo.cms.service.ProductManagerService com.jodo.cms.controllers.ProductController.productManager; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'productManager': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: com.jodo.cms.dao.ProductTypeDao com.jodo.cms.service.impl.ProductManagerServiceimpl.productTypeDao; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'productTypeDao' defined in file [/home/jodo/Server/Tomcat/webapps/jodocms/WEB-INF/classes/com/jodo/cms/dao/impl/ProductTypeDaoImpl.class]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Could not instantiate bean class 

    [com.jodo.cms.dao.impl.ProductTypeDaoImpl]: Constructor threw exception; nested exception is java.lang.ClassCastException: java.lang.Class cannot be cast to java.lang.reflect.ParameterizedType
        at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:287)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1106)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:517)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
        at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:294)
        at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:225)
        at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:291)
        at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
        at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:585)
        at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:913)
        at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:464)
        at org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:631)
        at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:588)
        at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:645)
        at org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:508)
        at org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:449)
        at org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:133)
        at javax.servlet.GenericServlet.init(GenericServlet.java:158)
        at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1279)
        at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1192)
        at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:1087)
        at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:5210)
        at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5493)
        at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
        at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:901)
        at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:877)
        at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:632)
        at org.apache.catalina.startup.HostConfig.deployWAR(HostConfig.java:1073)
        at org.apache.catalina.startup.HostConfig$DeployWar.run(HostConfig.java:1857)
        at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471)
        at java.util.concurrent.FutureTask.run(FutureTask.java:262)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
        at java.lang.Thread.run(Thread.java:744)
    Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: com.jodo.cms.service.ProductManagerService com.jodo.cms.controllers.ProductController.productManager; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'productManager': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: com.jodo.cms.dao.ProductTypeDao com.jodo.cms.service.impl.ProductManagerServiceimpl.productTypeDao; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'productTypeDao' defined in file [/home/jodo/Server/Tomcat/webapps/jodocms/WEB-INF/classes/com/jodo/cms/dao/impl/ProductTypeDaoImpl.class]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [com.jodo.cms.dao.impl.ProductTypeDaoImpl]: Constructor threw exception; nested exception is java.lang.ClassCastException: java.lang.Class cannot be cast to java.lang.reflect.ParameterizedType
        at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:506)
        at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87)
        at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:284)
        ... 33 more
    Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'productManager': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: com.jodo.cms.dao.ProductTypeDao com.jodo.cms.service.impl.ProductManagerServiceimpl.productTypeDao; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'productTypeDao' defined in file [/home/jodo/Server/Tomcat/webapps/jodocms/WEB-INF/classes/com/jodo/cms/dao/impl/ProductTypeDaoImpl.class]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [com.jodo.cms.dao.impl.ProductTypeDaoImpl]: Constructor threw exception; nested exception is java.lang.ClassCastException: java.lang.Class cannot be cast to java.lang.reflect.ParameterizedType
        at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:287)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1106)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:517)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
        at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:294)
        at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:225)
        at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:291)
        at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
        at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:269)
        at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
        at org.springframework.beans.factory.support.DefaultListableBeanFactory.findAutowireCandidates(DefaultListableBeanFactory.java:848)
        at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:790)
        at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:707)
        at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:478)
        ... 35 more
    Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: com.jodo.cms.dao.ProductTypeDao com.jodo.cms.service.impl.ProductManagerServiceimpl.productTypeDao; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'productTypeDao' defined in file [/home/jodo/Server/Tomcat/webapps/jodocms/WEB-INF/classes/com/jodo/cms/dao/impl/ProductTypeDaoImpl.class]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [com.jodo.cms.dao.impl.ProductTypeDaoImpl]: Constructor threw exception; nested exception is java.lang.ClassCastException: java.lang.Class cannot be cast to java.lang.reflect.ParameterizedType
        at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:506)
        at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87)
        at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:284)
        ... 48 more
    Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'productTypeDao' defined in file [/home/jodo/Server/Tomcat/webapps/jodocms/WEB-INF/classes/com/jodo/cms/dao/impl/ProductTypeDaoImpl.class]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [com.jodo.cms.dao.impl.ProductTypeDaoImpl]: Constructor threw exception; nested exception is java.lang.ClassCastException: java.lang.Class cannot be cast to java.lang.reflect.ParameterizedType
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:997)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:943)
        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:294)
        at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:225)
        at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:291)
        at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
        at org.springframework.beans.factory.support.DefaultListableBeanFactory.findAutowireCandidates(DefaultListableBeanFactory.java:848)
        at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:790)
        at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:707)
        at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:478)
        ... 50 more
    Caused by: org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [com.jodo.cms.dao.impl.ProductTypeDaoImpl]: Constructor threw exception; nested exception is java.lang.ClassCastException: java.lang.Class cannot be cast to java.lang.reflect.ParameterizedType
        at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:162)
        at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:76)
        at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:990)
        ... 61 more
    Caused by: java.lang.ClassCastException: java.lang.Class cannot be cast to java.lang.reflect.ParameterizedType
        at com.jodo.cms.dao.impl.GenericDaoImpl.<init>(GenericDaoImpl.java:42)
        at com.jodo.cms.dao.impl.ProductTypeDaoImpl.<init>(ProductTypeDaoImpl.java:19)
        at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
        at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
        at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
        at java.lang.reflect.Constructor.newInstance(Constructor.java:526)
        at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:147)
        ... 63 more


类 GenericDaoImpl 详细信息

public abstract class GenericDaoImpl<T extends AbstractJpaEntity> implements GenericDao<T> {
protected Class<T> entityClass;
Logger logger = Logger.getLogger(GenericDaoImpl.class);
@PersistenceContext
protected EntityManager em;
    public EntityManager getEntityManager() {
        return this.em;
    }
    @SuppressWarnings("unchecked")
    public GenericDaoImpl() {
        ParameterizedType genericSuperclass = (ParameterizedType) getClass().getGenericSuperclass();
        this.entityClass = (Class<T>) genericSuperclass.getActualTypeArguments()[0];
    }

public void persist(T entity) throws JodoException {
    try {
        em.persist(entity);
        em.flush();
    } catch (ConstraintViolationException cve) {
        throw new JodoException(cve.getCause(), "constraints violated", cve);
    }
}...


我无法更改 AbstractJpaEntity、GenericDao 和 GenericDaoImpl,因为它已经用于合并许多其他未扩展 ProductTypeDomain 的实体。

谢谢

最佳答案

在这个类声明中

public class ProductTypeDaoImpl extends GenericDaoImpl implements ProductTypeDao

您正在使用 GenericDaoImplProductTypeDao 作为原始类型。 Start by reading why you shouldn't use them.

您使用原始类型的事实会导致此处出现问题

ParameterizedType genericSuperclass = (ParameterizedType) getClass().getGenericSuperclass();

getGenericSuperclass() 将返回一个 Class 实例,因为 GenericDaoImpl,在

public class ProductTypeDaoImpl extends GenericDaoImpl implements ProductTypeDao

未参数化,因此不是 ParameterizedType。然后转换失败。

解决方案是在类声明中参数化这两种类型。从您的代码中并不能立即看出这些类型参数应该是什么,但是 GenericTypeDao 可能应该采用 ProductTypeDomain

public class ProductTypeDaoImpl extends GenericDaoImpl<ProductTypeDomain> implements ProductTypeDao

你的接口(interface) ProductTypeDao 应该声明为

public interface ProductTypeDao extends GenericDao<ProductTypeDomain> {

关于java.lang.ClassCastException : java. lang.Class 无法转换为 java.lang.reflect.ParameterizedType,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23074446/

相关文章:

java - Hibernate:复合 id 服务

java - Hibernate manyToMany 只返回一个元素

java - 用于纯服务器端 war-packaged Java EE 6 应用程序的 Maven 原型(prototype)?

java - 在Java中初始化ivars

java - 在没有 Spring MVC 的 portlet 中使用 Spring

java - Spring Boot 生成无效的 MySQL 查询 (only_full_group_by)

mysql - 在 Spring Boot 中从 mysql 读取时出现奇怪的超时

java - 使用 log4j 异步发送电子邮件

java - DateTimeFormat 接受 json 请求中的数字而不是日期格式

mysql - 更新id有问题