您的位置:首页 > 编程语言 > Java开发

利用Java反射机制模拟框架利用类加载器加载配置文件

2014-05-17 20:13 330 查看
通过配置文件配置,然后利用Java反射创建一个集合。

项目结果:



我们在config.properties配置文件中指定要创建的类名:

className = java.util.ArrayList


在测试代码中加载配置文件,然后利用反射创建集合:

public class FrameWorkReflectTest {

	public static void main(String[] args) throws Exception {
		
		/*通过类加载器加载配置文件*/
		InputStream ins = FrameWorkReflectTest.class.getClassLoader().getResourceAsStream("com/lixue/framereflect/config.properties");
		/*创建Properties对象*/
		Properties props = new Properties();
		props.load(ins);
		/*关闭流*/
		ins.close();
		/*从配置文件中获取属性*/
		String className = props.getProperty("className");
		
		/*通过反射创建一个集合(此时的className为java.util.ArrayList)*/
		Collection collections = (Collection) Class.forName(className).newInstance();
		
		/*往collection集合中添加数据*/
		collections.add(1);
		collections.add("廖泽民");
		collections.add("男");
		
		/*打印集合元素*/
		System.out.println(collections);
		
	}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐