1.创建4个类:
public class A {
private int i;
public int getI() {
return i;
}
public void setI(int i) {
this.i = i;
}
public void a() {
System.out.println("好嗨哟~");
}
}
public class B {
public void b() {
System.out.println("感觉人生已经达到了高潮~");
}
}
public class C {
public void c() {
System.out.println("感觉人生已经达到了巅峰~");
}
}
public class D {
public void d() {
System.out.println("好炫彩~");
}
}
在d盘或者src目录下新建文件config.txt,内容为以上4个类的包路径加方法名:
config.txt
com.A;a
com.B;b
com.C;c
com.D;d
创建测试类:
public class Runner {
//保存数据的数组
private static ArrayList<String> list = new ArrayList<>();
static {
try {
//文件路径
// String path = Runner.class.getResource("/config").getPath();
// //如果路径有中文会乱码.
// path= URLDecoder.decode(path,"UTF-8");
//读取文件的组合 BR(BufferedReader)+ISR(InputStreamReader)+FIS(FileInputStream)
BufferedReader in =
new BufferedReader(
new InputStreamReader(
// new FileInputStream("path"), "GBK"));
new FileInputStream("D:\\config.txt"), "GBK"));
//循环读取文件
String line;
while((line = in.readLine()) != null) {
//替换空格
line = line.replaceAll(" ", "");
if(line.length() == 0) {
continue;
}
list.add(line);
}
//关闭流
in.close();
System.out.println(list);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static void launch() throws Exception {
for (String s : list) {
//拆分字符串
String[] a = s.split(";");
//获取“类对象”
Class<?> c = Class.forName(a[0]);
//新建实例执行无参构造
Object obj = c.newInstance();
//获取方法
Method m = c.getMethod(a[1]);
//反射调用该方法
m.invoke(obj);
}
}
public static void main(String[] args) throws Exception {
Runner.launch();
}
}
输出结果:
[com.A;a, com.B;b, com.C;c, com.D;d]
好嗨哟~
感觉人生已经达到了高潮~
感觉人生已经达到了巅峰~
好炫彩~