views:

47

answers:

2

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()?

+1  A: 

You need extcos:

select(javaClasses()).from("your.package").returning(allAnnotatedWith(YourAnnotation.class))

Also supports thoseImplementing and thoseExtending etc...

See: http://sourceforge.net/projects/extcos/

Spring also contains similar code for it's component scanning that is easily adapted.

Pablojim
Cool! I like it. It has necessary features, simple in usage, and (I almost sure) it'll be very interesting to investigate the implementation (because I don't know yet how to do the same things myself).
Roman