现在的位置: 首页 > 综合 > 正文

java 高新技术【6】 反射开发框架以及用 类加载器 管理资源和配置文件

2013年11月08日 ⁄ 综合 ⁄ 共 2090字 ⁄ 字号 评论关闭

//第一种方士:【把文件放在  项目名 下  】 尽量  面向父类 和 接口编程 。
InputStream ips = new FileInputStream("config.properties");

第二种 :com/itm/day1/config.properties 用类加载器的方式:

在classpath 那些指定的目录下,逐一的去查找 你要加载的那个文件。 bin是用户的那个路径。
在  classPath的根目录下  逐一的查找。

InputStream ips =
 ReflectTest2.class.getClassLoader().getResourceAsStream("com/itm/day1/config.properties");

第三种:com/itm/day1/config.properties
InputStream ips =  ReflectTest2.class.getResourceAsStream("config.properties");

第四种:com.itm.day1.resource/config.properties
InputStream ips =  ReflectTest2.class.getResourceAsStream("resource/config.properties");


import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Collection;
import java.util.Properties;

public class ReflectTest2 {

	/**
	 * 
	 * 一定要用完整的路径,但完整的路径不是 硬编码。而是计算出来的;。
	 * @param args
	 * @throws Exception 
	 */
	public static void main(String[] args) throws Exception {
		
		//第一种方士:【把文件放在  项目路径下 如:你的java工程名为:test,则放在test下】 尽量  面向父类 和 接口编程 。
		InputStream ips = new FileInputStream("config.properties");
		
		/* 第二种 :用类加载器的方式:
		
		 在classpath 那些指定的目录下,逐一的去查找 你要加载的那个文件。 bin是用户的那个路径。
		 在  classPath的根目录下  逐一的查找。
		
		InputStream ips =  ReflectTest2.class.getClassLoader().getResourceAsStream("com/itm/day1/config.properties");*/
		
		// 第三种:com/itm/day1/config.properties
//		InputStream ips =  ReflectTest2.class.getResourceAsStream("config.properties");
		
//		 第四种:com.itm.day1.resource
//		 InputStream ips =  ReflectTest2.class.getResourceAsStream("resource/config.properties");
		
		
		
		// Properties 相当于 hashMap,但是 : 可以把自己的内存的键值对  存到 硬盘文件内去、。
		//也可以在 初始化的时候,从一个文件 把自己的键值对 加载进来。
		Properties props  = new Properties();
		props.load(ips);
		ips.close();// 把操作系统的东西  干掉。
		
		// 拿到 文件的 key值
		String className = props.getProperty("className");
		Collection collections = (Collection) Class.forName(className).newInstance();
		
		ReflectPoint pt1 = new ReflectPoint(3,3);
		ReflectPoint pt2 = new ReflectPoint(5,5);
		ReflectPoint pt3 = new ReflectPoint(3,3);
		collections.add(pt1);
		collections.add(pt2);
		collections.add(pt3);
		collections.add(pt1);
		
		
		System.out.println(collections.size());
	}

}

className=java.util.HashSet

小结:
1.用IO流的方式读写文件,通常是用绝对路径,但是为了通用性,这个绝对路径通常不要硬编码,而是运算出来的。
2.类加载器在各种框架中普遍应用,无论是直接的加载(如1),还是简化的加载(如2,3,4),它们的本质都是ClassLoader。
3.简化的类加载器可以使用相对路径,也可以使用绝对路径。


有关类加载器的深入探讨:http://www.ibm.com/developerworks/cn/java/j-lo-classloader/


抱歉!评论已关闭.