如果你要创建的对象依赖于某个文件,那么可以将信息写到配置文件中。
现在配置文件config.properties中有一个名称值对,如何加载它?通过InputStream对象和Properties对象即可轻松办到。
通常分为5步
第一步:得到文件的流对象。第一种方法直接new对象,后面两种都是通过类加载器加载
InputStream is = obj.class.getClassLoader().getResourceAsStream("cn/itcast/day1/config.properties");// 相对于包所在路径
InputStream is = obj.class.getResourceAsStream("resource/config.properties"); // 相对于当前类所在路径
第二步:创建Properties对象
Properties prop = new Properties();
第三步:用Properties对象加载流文件
prop.load(is);
is.close(); // 关闭与系统关联的资源,否则即使对象没了,资源还在被占用。
第四步:获取配置文件中的属性
String className = prop.getProperty("className");
第五步:根据配置信息动态创建对象:
Collection collections = (Collection) Class.forName(className).newInstance();