Search code examples
gwtguicegwtp

Assisted Injection with enum parameter


I have multiple presenter widgets that I pull from a clientfactory using assisted injection.

public interface FieldFactory {

    TextboxPresenterWidget createTextBoxWidget(Field field);
    BooleanPresenterWidget createBooleanWidget(Field field);
        ...
}

This currently works fine, but what I want to do is be able to create the widget I want without having to call it out specifically and instead be able to pass in it's type as part of the injection to get the correct PresenterWidget back.

Each 'Field' object has an enum property with what type it is... I am wondering if there is a way, how I would go about doing this.

Preferably my factory would look more like this:

public interface FieldFactory {

    TextboxPresenterWidget create(Field field, FieldType type);
    BooleanPresenterWidget create(Field field, FieldType type);
        ...
}

This would make my impl code be more like:

...
for(Field field : fields) {
    addToSlot(SLOT_NAME, fieldFactory.create(field, field.getType()));
}
...

Thanks for any input, it is much appreciated!


Solution

  • The switch…case on the enum values would have to be done somewhere anyway, and while I could understand you'd prefer to have it generated for you rather than hand-coded, GIN won't do it and it'd probably require more (or at least as many) configuration code than the switch code itself.

    So how about a hand-written factory that defers to the assisted-inject one?

    public class FieldFactory {
      @Inject AssistedFieldFactory factory;
    
      public PresenterWidget create(Field field) {
        switch (field.getType()) {
        case TEXTBOX:
          return factory.createTextBoxWidget(field);
        case BOOLEAN:
          return factory.createBooleanWidget(field);
        default:
          throw new IllegalArgumentException();
        }
      }
    }