使用简单的例子模拟Spring动态加载类;
思路很简单
创建一个容器 通过 反射 来得到一个类的对象。
通过流 来加载配置文件 得到一个类的全类名(包名+类名)
再通过 反射 获取这个类的class
最后 调用instance 方法 实例化这个对象。
来看下代码
spring容器
public class BeanFactory {
//获取对象的方法
public Object getBean(String beanName) {
Object object = null;
Properties properties = new Properties();
try {
//加载配置文件
properties.load(new FileInputStream("写配置文件的路径"));
//获取key 值 就是类全名
String className = (String)properties.get(beanName);
//通过类全名获取镜子对象
Class c = Class.forName(className);
// 获取实例对象
object = c.newInstance();
} catch (Exception e) {
e.printStackTrace();
}
return object;
}
}
学生类
public class Student {
private int age;
private int id;
public void say(){
System.out.println("调用say方法");
}
}
测试程序
public class ClassTest {
public static void main(String[] args) {
BeanFactory beanFactory = new BeanFactory();
Student student = (Student)beanFactory.getBean("student");
student.say();
}
}
配置文件
student=com.test.Student
输出结果
通过这种方式 就很灵活的生成了需要用的类。 如果要进行改动的话 就只要改动配置文件,其他不需改变。
再来过一遍流程
通过流加载配置文件 -> 获取到全类名 -> 反射 生成需要的类 -> 返回实例对象。
这就是Spring加载类的简单实现方式。