java.lang.ClassCastException: com.sun.proxy.$Proxy7 cannot be cast to
Posted 谷哥的小弟
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java.lang.ClassCastException: com.sun.proxy.$Proxy7 cannot be cast to相关的知识,希望对你有一定的参考价值。
版权声明
- 本文原创作者:谷哥的小弟
- 作者博客地址:http://blog.csdn.net/lfdfhl
报错描述
小伙伴在项目使用了Spring框架,涉及到了通知和切面,在配置Spring时,控制台报错:
java.lang.ClassCastException: com.sun.proxy.$Proxy7 cannot be cast to cn.com.dao.AccountDaoImpl
这是为什么呢?我们先来瞅瞅项目里的代码
配置文件中代码如下:
<bean id="accountDao" class="cn.com.dao.AccountDaoImpl"></bean>
请注意class的值cn.com.dao.AccountDaoImpl,它是cn.com.dao.AccountDao接口的实现类。
在测试类中代码如下:
ApplicationContext applicationContext=new ClassPathXmlApplicationContext("applicationContext.xml");
AccountDaoImpl accountDao=(AccountDaoImpl) applicationContext.getBean("accountDao");
运行之后就报了错误:
java.lang.ClassCastException: com.sun.proxy.$Proxy7 cannot be cast to cn.com.dao.AccountDaoImpl
解决方案
发生该错误的原因在于:不能将代理对象转换为接口的实现类AccountDaoImpl;因为它们两者在本质上是同级的!
所以,应该使用两者的共同接口来接收applicationContext.getBean(“accountDao”)的返回值;代码如下:
ApplicationContext applicationContext=new ClassPathXmlApplicationContext("applicationContext.xml");
AccountDao accountDao=(AccountDao) applicationContext.getBean("accountDao");
以上是关于java.lang.ClassCastException: com.sun.proxy.$Proxy7 cannot be cast to的主要内容,如果未能解决你的问题,请参考以下文章