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


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());

	}

}

四、配置文件管理




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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值