[code="java"]CategoryDao dao = new CategoryDaoImpl();[/code]很好理解
但是下面代码我几有点迷惑了
[code="java"]package cn.factory;
import cn.dao.CategoryDao;
import cn.dao.impl.CategoryDaoImpl;
import cn.domain.Category;
public class DaoFactory {
private DaoFactory(){}
private static DaoFactory instance = new DaoFactory();
public static DaoFactory getinstance(){
return instance;
}
public <T> T createDao(String classname,Class<T> clazz){
try {
T t = (T) Class.forName(classname).newInstance();
return t;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}[/code]
不用泛型
[code="java"]
public CategoryDao createCategoryDao(String classname){
try {
CategoryDao dao = (CategoryDao) Class.forName(classname).newInstance();
return dao;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
[/code]
得到实例
[code="java"]
CategoryDao dao = DaoFactory.getinstance().createDao("cn.dao.impl.CategoryDaoImpl",CategoryDao.class);
//CategoryDao dao = DaoFactory.getinstance().createDao("cn.dao.impl.CategoryDaoImpl");
[/code]
很明显Class.forName(classname).newInstance()得到是接口实现类为什么还需要强转
想了很久[code="java"]CategoryDao dao = new CategoryDaoImpl();[/code]两个感觉矛盾了 :cry: .
求解... :oops: