从配置文件读取内容进行实例化
读取配置文件的类
class PropertyMgr {
private static Properties props = new Properties();
static {
try {
props.load(Test.class.getClassLoader().getResourceAsStream("observer/observer.properties"));
} catch (IOException e) {
e.printStackTrace();
}
}
public static String getProperty(String key) {
return props.getProperty(key);
}
}
配置文件
observers=com.bjsxt.dp.observer.Dad,com.bjsxt.dp.observer.GrandFather,com.bjsxt.dp.observer.Dog
使用配置文件
public static void main(String[] args) {
Child c = new Child();
String[] observers = PropertyMgr.getProperty("observers").split(",");
for(String s : observers) {
try {
c.addWakenUpListener((WakenUpListener)(Class.forName(s).newInstance()));
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
new Thread(c).start();
}
网友评论