public class Reflection {
public void sayHello(String theClass){
//Since Mod classes are in package 'mod', we precede their name accordingly.
Class aClass = Class.forName("mod." + theClass);
aClass.getMethod("sayHi").invoke(aClass.newInstance());
}
public static void main(String[] args) {
//Get a list of the compiled classes in the 'mod' folder
String path = "./bin/mod";
String fileName;
File folder = new File(path);
List<File> fileList = Arrays.asList(folder.listFiles());
//Iterate through the list of classes to invoke their methods
Iterator<File> it = fileList.iterator();
while(it.hasNext()){
fileName = it.next().getName();
//When invoking the sayHello method, we remove the file extension
new Reflection().sayHello(fileName.replace(".class", ""));
}
}
}
ModA 类:
public class ModA {
public void sayHi(){
System.out.println("Hi! I'm ModA.");
}
}
ModB 类:
public class ModB {
public void sayHi(){
System.out.println("Hi! I'm ModB.");
}
}
请注意:
- 为了阐明示例,我删除了一些必要的异常处理。
- Mod 类位于一个名为“mod”的包中。编译后,它们存在于 bin/mod 中。可能有一种更清洁的方式来扫描它们。
- Mod 类被编译、打包到一个 jar 中并包含在构建路径中。