一、反射的应用-->实现框架功能
- 框架,比如:
- 我做房子卖给用户住,由用户自己安装门窗和空调
- 我做的房子就是框架,用户需要使用我的框架,把门窗插入进我提供的框架中
- 框架与工具有区别,工具类被用户的类调用,而框架则是调用用户提供的类
- 框架要解决的核心问题,比如:
- 我在写框架(房子)的时候,你这个用户可能还在上小学
- 还不会编程呢,我写的框架程序怎样能调用到你以后写的类(门窗)呢?
- 因为在写程序时无法知道要被调用的类名,
- 所以,在程序中无法直接new某个类的实例对象,就需要用反射方式来做
二、综合案例
采用配置文件加反射的方式创建ArrayList和HashSet的实例对象,比较运行结果的差异
import java.util.*;
import java.io.*;
public class HashCodeTest {
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 col = (Collection) Class.forName(className).newInstance();
Student stu1 = new Student("zhangsan",20);
Student stu2 = new Student("lisi",18);
Student stu3 = new Student("wangwu",25);
Student stu4 = new Student("zhangsan",20);
col.add(stu1);
col.add(stu2);
col.add(stu3);
col.add(stu4);
col.add(stu1);
stu1.age = 15;
System.out.println(col.size());
}
}
class Student
{
String name;
int age;
Student(String name,int age)
{
this.name = name;
this.age = age;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + age;
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Student other = (Student) obj;
if (age != other.age)
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
public String toString()
{
return name+":"+age;
}
}