您的位置:首页 > 其它

使用类加载器加载配置文件

2014-12-31 10:31 232 查看
package com.franky.reflex;

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

/**
 * @描述 使用类加载器加载配置文件	
 * @作者 franky
 * @日期 2014-12-31 上午10:15:58
 */
public class InvokeCollectionWithReflet {

	/**
	 * @param args
	 * @throws Exception 
	 */
	public static void main(String[] args) throws Exception {
		//加载方式一:用类加载器加载配置文件为输入流,文件在根目录下
		//InputStream inputStream = InvokeCollectionWithReflet.class.getClassLoader().getResourceAsStream("config.properties");
		//加载方式二:直接用Class对象调用,内部使用的还是classLoader,使用的是绝对路径
		InputStream inputStream = InvokeCollectionWithReflet.class.getResourceAsStream("/config.properties");
		Properties p = new Properties();
		p.load(inputStream);
		String className = p.getProperty("className");
		//利用反射得到该类的Class对象,并实例化
		Class clazz = Class.forName(className);
		Collection collection = (Collection) clazz.newInstance();
		
		Point p1 = new Point(3,3);
		Point p2 = new Point(4,4);
		Point p3 = new Point(3,3);
		//添加元素对象
		collection.add(p1);
		collection.add(p2);
		collection.add(p3);
		
		System.out.println(collection.size());
		
		
	}

}

class Point{
	private int x;
	private int y;
	
	/**
	 * @return the x
	 */
	public int getX() {
		return x;
	}
	/**
	 * @param x the x to set
	 */
	public void setX(int x) {
		this.x = x;
	}
	/**
	 * @return the y
	 */
	public int getY() {
		return y;
	}
	/**
	 * @param y the y to set
	 */
	public void setY(int y) {
		this.y = y;
	}
	public Point(int x, int y) {
		super();
		this.x = x;
		this.y = y;
	}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: