zoukankan      html  css  js  c++  java
  • 开发Spring过程中几个常见异常(三):java.lang.ClassCastException: com.sun.proxy.$Proxy4 cannot be cast to com.edu.aop.ArithmeticCalculatorImpl at com.edu.aop.Main.main(Main.java:11)

    这个异常是在开发Spring案例时遇到的。

    贴一下完整异常信息:

    Exception in thread "main" java.lang.ClassCastException: com.sun.proxy.$Proxy4 cannot be cast to com.edu.aop.ArithmeticCalculatorImpl
        at com.edu.aop.Main.main(Main.java:11)

    原因:Spring AOP是实现AOP的一种技术,是采用“动态代理技术”实现的。

    在该案例中用到了接口,其中小编定义了一个接口ArithmeticCalculator,然后用实体类ArithmeticCalculatorImpl实现了这个接口。

    错误代码定位在(此处贴出代码第二句):

    ApplicationContext act=new ClassPathXmlApplicationContext("applicationContext.xml");
    ArithmeticCalculatorImpl arithmetic=(ArithmeticCalculatorImpl)act.getBean("arithmetic");

    再贴一下配置文件中配置信息:

    <!-- 配置bean -->
    <bean id="arithmetic" class="com.edu.aop.ArithmeticCalculatorImpl"></bean>

    可以看到配置的bean是接口的实现类,那么String AOP技术对其进行动态代理,代理的结果对象和这个接口的实现类是同级的。也就是说代理对象和小编定义的接口实现类分别实现了该接口,二者之间根据java语言的转换原则是不能转换的,因此抛出转换异常。

    当把转换类型换成接口类型时,就可解决这个异常了。即将红色代码部分改成:

    ArithmeticCalculator arithmetic=(ArithmeticCalculator)act.getBean("arithmetic");

    参考博客:

    http://blog.csdn.net/yinzn2011/article/details/46455973

    http://blog.csdn.net/a1491918446/article/details/48715247

  • 相关阅读:
    大数据时代-散记
    MongoDB命令行操作
    easyui获取日期datebox中的值
    linux文件系统学习
    Linux中部署JAVA程序
    百度Clouda的初步探索
    global.asax?app.config?webconfig??
    Android adb install INSTALL_FAILED_DEXOPT
    Android SharedPreferences 权限设置
    vim 支持 markdown 语法
  • 原文地址:https://www.cnblogs.com/dudududu/p/8487451.html
Copyright © 2011-2022 走看看