第四课:通过配置文件获取对象(Spring框架中的IOC和DI的底层就是基于这样的机制)

时间:2021-07-21 19:53:11

首先在D盘创建一个文件hero.txt,内容为:com.hero.Hero(此处必须是Hero的完整路径)

接下来是Hero类

package com.hero;

public class Hero {
String name;
int id; public Hero() {
super();
// TODO Auto-generated constructor stub
} public Hero(String name, int id) {
super();
this.name = name;
this.id = id;
} public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} public int getId() {
return id;
} public void setId(int id) {
this.id = id;
} static String copyright; static {
System.out.println("初始化 copyright");
copyright = "版权由Riot Games公司所有";
} @Override
public String toString() {
return "Hero [name=" + name + ", id=" + id + "]";
} }

然后是Test类测试

package com.hero;

import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException; public class TestReflection4 {
public static void main(String[] args) throws InterruptedException {
Hero h = getHero();
System.out.println(h);
} public static Hero getHero() { File f = new File("D:/hero.txt"); try (FileReader fr = new FileReader(f)) {
String className = null;
char[] all = new char[(int) f.length()];
  //把文件里的数据读到all这个char数组里面
fr.read(all);
  //String的构造方法,也可以用className=String.valueOf(all);
className = new String(all);
Class clazz=Class.forName(className);
Constructor c= clazz.getConstructor();
Hero h= (Hero) c.newInstance();
h.setName("a");
return h;
} catch (Exception e) {
e.printStackTrace();
return null;
} }
}