下面的程序转摘与 疯狂java
主要功能:实现了一个简单的对象池,该对象池就会根据配置文件读取key-value对,然后创建这些对象,并将这些对象放入一个HashMap
package Tjava;
import java.io.FileInputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import org.omg.CORBA.PUBLIC_MEMBER;
public class ObjectPoolFactory {
//定义一个对象名池,前面是对象名,后面 是实际的对象
private Map<String,Object> objectPool = new HashMap<String, Object>();
//定义一个创建对象的方法
private Object createObject(String clazzName) throws InstantiationException,IllegalAccessException,ClassNotFoundException
{
Class<?> clazz = Class.forName(clazzName);
return clazz.newInstance();
}
//根据指定文件来初始化对象池
public void initPool(String filename) throws InstantiationException,IllegalAccessException,ClassNotFoundException
{
try (FileInputStream fis = new FileInputStream(filename)){
Properties props = new Properties();
props.load(fis);
for(String name : props.stringPropertyNames()){
objectPool.put(name,createObject(props.getProperty(name)));
}
} catch (Exception e) {
// TODO: handle exception
System.out.println("读取"+ filename +"异常");
}
}
public Object getObject(String name){
return objectPool.get(name);
}
public static void main(String[] args) throws Exception{
ObjectPoolFactory PF = new ObjectPoolFactory();
PF.initPool("F:\\wsdworkspace\\java\\src\\obj.txt"");
System.out.println(PF.getObject("a"));
System.out.println(PF.getObject("a"));
}
}
obj.txt 如下:
a = java.util.Date
b= javax.swing.JFrame