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

7

我使用泛型创建了接口和类的层次结构,但是搞砸了一切。
最顶层的类是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{}

“GenericDao”接口定义

public interface GenericDao<T> {...

抽象类GenericDaoImpl(该类具有像persist、merge等通用功能)

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

接口 ProductTypeDao

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

Spring仓库类ProductTypeDaoImpl

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

在 Spring 的服务类 ProductManagerServiceImpl 中,我正在自动注入 repository productTypeDao。
@Service("productManager")
public class ProductManagerServiceimpl implements ProductManagerService{
    @Autowired
    ProductTypeDao productTypeDao;

在运行代码时,它给我以下错误:
Caused by: org.springframework.beans.factory.BeanCreationException:无法自动装配字段:com.jodo.cms.controllers.ProductController.productManager;嵌套异常是org.springframework.beans.factory.BeanCreationException:创建bean时发生错误:注入自动装配的依赖项失败;嵌套异常是org.springframework.beans.factory.BeanCreationException:无法自动装配字段:com.jodo.cms.service.impl.ProductManagerServiceimpl.productTypeDao;嵌套异常是org.springframework.beans.factory.BeanCreationException:在文件[/home/jodo/Server/Tomcat/webapps/jodocms/WEB-INF/classes/com/jodo/cms/dao/impl/ProductTypeDaoImpl.class]中定义的名为'productTypeDao'的bean创建失败;嵌套异常是org.springframework.beans.BeanInstantiationException:无法实例化bean类[com.jodo.cms.dao.impl.ProductTypeDaoImpl]:构造函数抛出异常;嵌套异常是java.lang.ClassCastException:java.lang.Class无法转换为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

通用数据访问对象实现类详情

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的其他实体。谢谢。

请展示您的 ProductTypeDaoImpl 构造函数及其所有父类构造函数。 - Sotirios Delimanolis
嗨,Sotirios,我没有为任何类定义显式构造函数。 - user811602
请发布剩余的堆栈跟踪信息。 - Sotirios Delimanolis
我已经在主问题中发布了堆栈跟踪。我不知道这是否是 SO 中的正确做法。 - user811602
你只需进行格式化。我想看一下 GenericDaoImpl 类。 - Sotirios Delimanolis
我的错误。GenericDaoImpl有构造函数,我漏掉了。 - user811602
3个回答

7
在这个类声明中:
public class ProductTypeDaoImpl extends GenericDaoImpl implements ProductTypeDao

您正在使用GenericDaoImplProductTypeDao作为原始类型。使用原始类型会引起问题,建议阅读这篇文章了解不使用原始类型的原因。
ParameterizedType genericSuperclass = (ParameterizedType) getClass().getGenericSuperclass();

GenericDaoImpl 中,getGenericSuperclass() 将返回一个 Class 实例。

public class ProductTypeDaoImpl extends GenericDaoImpl implements ProductTypeDao

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

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

public class ProductTypeDaoImpl extends GenericDaoImpl<ProductTypeDomain> implements ProductTypeDao

你的接口ProductTypeDao可能应该声明为

public interface ProductTypeDao extends GenericDao<ProductTypeDomain> {

6
如果在启用 R8 后发现此异常,您可能需要在 progaurd-rules.pro 文件中添加以下行:
-keep,allowobfuscation,allowshrinking class kotlin.coroutines.Continuation

-1

这是一个解决方案

public TO getTo() throws Exception {
    if(to == null) {
        try {
            to = ((Class<TO>) ((ParameterizedType) this.getClass().getGenericSuperclass())
                    .getActualTypeArguments()[0]).newInstance();
        } catch(ClassCastException cce) {
            cce.printStackTrace();
            to = ((Class<TO>) ((ParameterizedType) (((Class<TO>) this.getClass()
                    .getAnnotatedSuperclass().getType()).getGenericSuperclass()))
                            .getActualTypeArguments()[0]).newInstance();
        }
    }
    return to;
}

5
你可以多提供一些细节,解释为什么你的代码示例会起作用。这里的目标是提供一个每个人都能理解并支持代码示例的答案。 - Pancho

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接