2

I have a list of actions implementing the Action interface.

FooAction implements Action
BarAction implements Action

I want to be able to process each action in a List :-

List<Action> actions = new ArrayList<Action>;
..

for( Action action : actions)
    action.process();

Is it possible to get Guice (or spring !) to inject all the individual Actions into the actions list ? I know I can write code to manually create a set like this :-

Multibinder<Action> actionBinder = Multibinder.newSetBinder(binder(), Action.class);

actionBinder.addBinding().to( FooAction.class );
actionBinder.addBinding().to( BarAction.class );

But it would be nice if I could write new action classes that are picked up automatically and injected into my list? or is this just wishful thinking.

Chris Milburn
  • 862
  • 1
  • 12
  • 20

2 Answers2

2

As mlk eluded to, you're looking for a classpath scanner. We use reflections:

http://code.google.com/p/reflections/

You will probably want to look at their "getSubTypesOf" method. We use that, as well as their "getTypesAnnotatedWith" method extensively to find all classes of a certain flavor at startup so they can be bound to lists at startup.

robertvoliva
  • 902
  • 6
  • 6
1

Java does not know of all the available implementations. You would have to loop over all the classes in the class path and inspect them (see Find Java classes implementing an interface), the other option would be to inform Guice or Spring via configuration files in known locations (this is how plugins often work).

Community
  • 1
  • 1
Michael Lloyd Lee mlk
  • 14,561
  • 3
  • 44
  • 81
  • I know java dosnt know about this but is there a Guice or Spring annotation that causes the Guice binder to be populated for me (after all it could do it, if it wasnt a list) at run time, rather than me hard coding it by calling 'addBinding()' ? – Chris Milburn Mar 27 '12 at 14:57
  • No annotation exists in Guice. You would have to write it yourself. As stated above, Java does not know so you would have to scan the class path. – Michael Lloyd Lee mlk Mar 27 '12 at 15:00