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.");
}
}
類商業方法:
public class ModB {
public void sayHi(){
System.out.println("Hi! I'm ModB.");
}
}
請注意:
- 我已經刪除了一些必要的異常,以澄清的例子處理。
- Mod類位於名爲'mod'的包中。編譯後,它們出現在bin/mod中。可能有更清晰的掃描方式。
- Mod類被編譯,打包成一個jar包含在構建路徑中。
我標記爲'反射',因爲我有一種感覺它涉及(雖然我真的不知道它的任何事情)。如果你知道它是無關的,請說出來,或刪除它。 – Nathan 2013-02-09 21:02:06
我並不確切地知道如何,但我認爲你能夠以某種方式找到你的類路徑上的所有類,然後通過反射來加載它們。或者你可以找到.class文件,並通過一些機制加載它們(javassist應該可以工作,但可能還有其他的東西)。 Eclipse通過配置文件來做這些事情(就是加載它的插件)。等等......這一切都歸結爲尋找你可能想要在類路徑上使用的文件。 – kutschkem 2013-02-09 21:20:43
難道這是戰略設計模式的行動嗎? :http://en.wikipedia.org/wiki/Strategy_design_pattern – 2013-02-09 21:34:22