您的位置:首页 > 编程语言 > Java开发

Java高新技术之框架的概念及用反射技术开发框架的原理和配置文件

2012-01-11 16:05 796 查看
1、框架与框架要解决的核心问题
我做房子卖给用户住,由用户自己安装门窗和空调,我做的房子就是框架,用户需要使用我的框架,把门窗插入进我提供的框架中。框架与工具类有区别,工具类被用户的类调用,而框架则是调用用户提供的类。

2、框架要解决的核心问题
我在写框架(房子)时,你这个用户可能还在上小学,还不会写程序呢?我写的框架程序怎样能调用到你以后写的类(门窗)呢?

因为在写才程序时无法知道要被调用的类名,所以,在程序中无法直接new 某个类的实例对象了,而要用反射方式来做。

3、综合案例

先直接用new 语句创建ArrayList和HashSet的实例对象,演示用eclipse自动生成 ReflectPoint类的equals和hashcode方法,比较两个集合的运行结果差异。
然后改为采用配置文件加反射的方式创建ArrayList和HashSet的实例对象,比较观察运行结果差异。
elipse对资源文件的管理

config.properties 配置文件的内容:
className1=java.util.ArrayList

className2=java.util.HashSet

public class ReflectPoint
{
public int x;
public int y;

public ReflectPoint(int x, int y)
{
super();
this.x = x;
this.y = y;
}

public String toString()
{

return this.x+" "+this.y;
}

@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + x;
result = prime * result + y;
return result;
}

@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
final ReflectPoint other = (ReflectPoint) obj;
if (x != other.x)
return false;
if (y != other.y)
return false;
return true;
}
}
import java.util.*;
import java.io.*;
public class ReflectTest2
{

public static void main(String[] args)throws Exception
{
//一定要记住用完整的路径,但完整的路径不是硬编码,而是运算出来的。
//如:工程目录/内部所在路径
//InputStream in=new FileInputStream("config.properties");

//使用类的加载器获取流
//InputStream in=ReflectTest2.class.getClassLoader().getResourceAsStream("day01/config.properties");
/*一个类加载器能加载.class文件,那它当然也能加载classpath环境下的其他文件,既然它有如此能力,它没有理由不顺带提供这样一个方法。它也只能加载classpath环境下的那些文件。注意:直接使用类加载器时,不能以/打头。*/
InputStream in=ReflectTest2.class.getResourceAsStream("resources/config.properties");

Properties prop=new Properties();
prop.load(in);
in.close();//关闭系统资源
//String className1=prop.getProperty("className1");
String className2=prop.getProperty("className2");

//Collection collections=(Collection)Class.forName(className1).newInstance();
Collection collections=(Collection)Class.forName(className2).newInstance();

ReflectPoint rp1=new ReflectPoint(3,3);
ReflectPoint rp2=new ReflectPoint(5,6);
ReflectPoint rp3=new ReflectPoint(3,3);

collections.add(rp1);
collections.add(rp2);
collections.add(rp3);
collections.add(rp1);
System.out.println("collections:"+collections.size());

}

}


四、配置文件管理

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐