相信很多人 在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











