相信很多人 在CustomerDAO customerDAO=(CustomerDAO)DAOFactory.getDAO(CustomerDAO.class)处出现了ClassCastException,我也出现了这个问题,但经过思考,找出了问题的根源
首选看ClassToolKit这个类,返回是Class类型的对象
在DAOConfig类中,我们往hashMap中保存的也是Class对象,使用put方式时,JDK将Class造型成Object
在DAOFactory类中,书中使用Object dao=daoMap.get(daoInterface) 这里没有任何错误
关键在于CustomerDAO customerDAO=(CustomerDAO)DAOFactory.getDAO(CustomerDAO.class) 这个代码
我们取回来的虽然是一个Object类型的,但这个object是从Class造型过来的,我们怎么可以强制转换成CustomerDAO类型呢?当然会报ClassCastException了
解决方法是修改DAOFactory
![](https://i-blog.csdnimg.cn/blog_migrate/6810355c2f78c12e91b7997a8e8c583a.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/a41954a27d6ad96fa2c2cf816e677448.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/1327ab569c1ae82736693a50b8e33378.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/37c8bf68cdc3cc81759c34160776bc53.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/7ff8d92cded7e0ce15e7ca1acc870052.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/6a9c071a08f1dae2d3e1c512000eef41.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/37c8bf68cdc3cc81759c34160776bc53.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/7ff8d92cded7e0ce15e7ca1acc870052.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/6a9c071a08f1dae2d3e1c512000eef41.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/717446ca04a6125dc5b6b54e0fa14ab4.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/0196c3df5ea9e936f21e9932cca91014.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/6810355c2f78c12e91b7997a8e8c583a.gif)