简单的实现了ioc原理。配置文件为info.ini
第一行写调用的类名,例如a
第二行写调用的方法的传入参数,this is demo!
package com.reflect;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.lang.reflect.Method;
@SuppressWarnings("all")
public class Demo {
public static void main(String[] args) throws Exception {
// 读取配置文件
File file = new File(
"D:/workspace/DemoProject/src/com/reflect/info.ini");
// 將文件的內容加緩存區
BufferedReader br = new BufferedReader(new FileReader(file));
// 读第一行数据
String choice = br.readLine();
// 读第二行数据
String say = br.readLine();
// 通过第一行数据加载类
Class c = Class.forName("com.reflect." + choice);
// 得到该类的方法,以及方法的参数
Method method = c.getMethod("say", String.class);
//实例化对象。接口声明。
Human human = (Human) c.newInstance();
//调用human方法say
method.invoke(human, say);
}
}
interface Human {
public void say();
public void say(String words);
}
class a implements Human {
public void say() {
}
public void say(String words) {
System.out.println("i am a," + words);
}
}
class b implements Human {
public void say() {
}
public void say(String words) {
System.out.println("i am b," + words);
}
}
class c implements Human {
public void say() {
}
public void say(String words) {
System.out.println("i am c," + words);
}
}