黑马程序员--反射--实现一个简单的集合操作框架

 * 问题:
 * 已知一个Point类,如何从配置文件中获取具体的集合类,将一系列Point对象添加到集合,然后返回该集合?
 * 解决方案:
 * 由于具体集合类未知,所以不能直接编写操作方法,需要依据具体的集合称,生成字节码对象,
 * 再由字节码对象构造一个实例;
 * 这样就可以编写一个简单的框架,在未知具体类的情况下,将Point对象添加到集合中;

 * 关键词: 反射 Class 框架


package zhangweicong.example.heima.reflex;

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

/**
 * 问题:
 * 已知一个Point类,如何从配置文件中获取具体的集合类,将一系列Point对象添加到集合,然后返回该集合?
 * 解决方案:
 * 由于具体集合类未知,所以不能直接编写操作方法,需要依据具体的集合称,生成字节码对象,
 * 再由字节码对象构造一个实例;
 * 这样就可以编写一个简单的框架,在未知具体类的情况下,将Point对象添加到集合中;
 * 关键词: 反射 Class 框架
 */
public class ReflexFrame {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		
		Point p1=new Point(1, 2);
		Point p2=new Point(2, 3);
		Point p3=new Point(3, 4);
		ReflexFrame  reflexFrame= new ReflexFrame();
		Collection collection = reflexFrame.getCollection("config.properties", "className");
		reflexFrame.add(collection, p1,p2,p3);
		
		System.out.println(collection.size()==3?"操作成功":"操作失败");
	}
	public Collection getCollection(String fileName,String property){
		InputStream inStream = null;
		Collection collection=null;
		Properties properties = new Properties();
		try{
			
			inStream=new FileInputStream(fileName);
			properties.load(inStream);
			collection = (Collection )Class.forName(properties.getProperty(property)).newInstance();
			
		}catch(IOException e){
			e.printStackTrace();
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {		
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}finally{
			
			try{
				if(inStream!=null)
					inStream.close();
			}catch(IOException e){
				e.printStackTrace();
			}
			
		}
		return collection;
	}
	public void add(Collection collection ,Point ... points){
		
		for(Point point : points){
			collection.add(point);
		}
	}
	
}
class Point{
	private int x;
	private int y;
	public Point(int x,int y){
		this.setX(x);
		this.setY(y);
	}
	public int getX() {
		return x;
	}
	public void setX(int x) {
		this.x = x;
	}
	public int getY() {
		return y;
	}
	public void setY(int y) {
		this.y = y;
	}
	public String toString(){ return "("+x+","+y+")"; }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值