const dex generate stat clas name 必须 nbsp
首先在 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;
- }
- }
- }
第四课:通过配置文件获取对象(Spring 框架中的 IOC 和 DI 的底层就是基于这样的机制)
来源: http://www.bubuko.com/infodetail-2170723.html