java类加载器加载文件

例子:采用配置文件加反射的方式创建ArrayList和HashSet的实例对象。

 1 //第一种方式:类加载器加载文件
 2 InputStream ips = ReflectTest2.class.getClassLoader().getResourceAsStream("cn/itcast/day1/config.properties");
 3 //第二种方式:class自带的方法加载
 4 InputStream ips = ReflectTest2.class.getResourceAsStream("resources/config.properties");
 5 Properties props = new Properties();//配置文件类似于HashMap
 6 props.load(ips);//加载文件
 7 ips.close();//关闭操作系统进程,但是java中对象没关闭,等待GC关闭
 8 //className为ArrayList或者HashMap
 9 String className = props.getProperty("className");
10 Collection collections = (Collection)Class.forName(className).newInstance();

 

posted @ 2016-11-25 14:57  阿飞博客  阅读(1353)  评论(0)    收藏  举报