package cn.itheima.factory;
import java.io.File;
import java.io.FileInputStream;
import java.util.Properties;
public class PubFactory {
//私有化实例工厂对象,使外界不能直接调用
private static PubFactory factory=new PubFactory();
//声明一个Properties类对象
private static Properties prop;
//构造方法私有化,使外界不能直接创建工厂
private PubFactory(){}
//静态代码块,类加载就执行,读取配置文件
static {
try{
//类加载器方式获得配置文件绝对路径
String path=PubFactory.class.getClassLoader().getResource("config.properties").getPath();
File file=new File(path);
prop=new Properties(); //创建Properties对象
prop.load(new FileInputStream(file));//加载配置文件
}catch (Exception e) {
e.printStackTrace();
}
}
public static PubFactory getFactory(){
return factory;
}
public E createInstance(String name,Class c){
try{
/*Class x = (Class) Class.forName(prop.getProperty(name));
return x.newInstance();*/
/*prop.getProperty(name)获取配置文件中name对应的字符串
* 比如传入的是dao,那就读取到cn.itheima.dao.CustDaoImpl
* 根据这个类名,就能创建这个类对应的字节码文件,也就是一个类。
*
* 利用泛型技术,第二个参数是一个类型的字节码,作用是限定返回值得对象的类型
* */
Class clazz=Class.forName(prop.getProperty(name));
//根据clazz类,创建对象
return (E)clazz.newInstance();
}catch (Exception e) {
e.printStackTrace();
throw new RuntimeException();
}
}
}