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

框架的概念及用反射技术开发框架的原理

2018-01-29 00:00 507 查看

一、框架与工具类概念

我做房子卖给用户住,由用户自己安装门窗和空调,我做的房子就是框架,用户需要使用我的框架,把门窗插入进我提供的框架中。框架与工具类有区别,工具类被用户的类调用,而框架则是调用用户提供的类

二、框架要解决的核心问题

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

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

三、综合案例

1、先直接用new 语句创建ArrayList和HashSet的实例对象,演示用eclipse自动生成 ReflectPoint类的equals和hashcode方法,比较两个集合的运行结果差异。

2、然后改为采用配置文件加反射的方式创建ArrayList和HashSet的实例对象,比较观察运行结果差异。

四、代码说明

1、HashCodeReflectTest.java

package staticimport.reflect;

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

public class HashCodeReflectTest {

public static void main(String[] args) throws Exception {
InputStream is = new FileInputStream("config.properties");
Properties props = new Properties();
props.load(is);

String className = props.getProperty("className");

Collection<ReflectPoint> reflectPoints = (Collection<ReflectPoint>) Class.forName(className).newInstance();

//		Collection<ReflectPoint> reflectPoints = new ArrayList<>();
//		Collection<ReflectPoint> reflectPoints = new HashSet<>();
ReflectPoint reflectPoint = new ReflectPoint(3, 3);
ReflectPoint reflectPoint2 = new ReflectPoint(5, 6);
ReflectPoint reflectPoint3 = new ReflectPoint(3, 3);

//测试hashCode作用
reflectPoints.add(reflectPoint);
reflectPoints.add(reflectPoint2);
reflectPoints.add(reflectPoint3);
reflectPoints.add(reflectPoint);

//测试内存泄漏
//		reflectPoint.y = 12;
//		reflectPoints.remove(reflectPoint);

System.out.println(reflectPoints.size());
}

}


2、config.properties

className=java.util.HashSet
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息