您的位置:首页 > 职场人生

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

2014-10-10 23:08 489 查看
* 问题:

* 已知一个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+")"; }
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐