相信很多人 在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
Class dao
=
(Class)daoMap.get(daoInterface);
if
(dao
==
null
)
...
{
try ...{
throw new Exception("error");
} catch (Exception e) ...{
System.out.println(e.getMessage());
}
}
return
dao.newInstance();
本文针对在使用CustomerDAO过程中出现的ClassCastException问题进行了深入分析,并提供了解决方案。问题出现在从Class对象强制转换为具体DAO实现类时。文章通过修改DAOFactory类的方法避免了异常的发生。

455





