I want to make my program initialization a bit "smarter".
I have several classes which represent commands. All these classes are immutable (i.e. creating only one instance of each should be enough for the whole application). All these classes implement Command
interface.
I think that the fact that some classes are placed in the same jar with a class with the main method (maybe even in 1 predefined package) and that these classes implement one known interface should give enough information to make it possible to automate creation of their instances.
How can I implement this feature? (Obviously, it's something tightly connected with reflection, and maybe, with java class loading mechanisms, but I'm not an expert in these fields).
I want to have something like this:
public static void init() {
...
Map<String, Command> commands = Maps.newHashMap();
for (Class clazz : findCommandImplementationsInThisJarFile()) {
//some try/catch stuff is ommited
Command command = clazz.newInstance();
commands.put(command.getName(), command);
}
...
}
How to implement the tricky method findCommandImplementationsInThisJarFile()
?