Search code examples
javaguiceassisted-inject

Guice FactoryModuleBuilder for lists of inputs


I've used Guice assisted injection and FactoryModuleBuilder to help construct adapter classes, where one class wraps another.

class MyClassWrapper implements SomeInterface {

  interface MyClassWrapper.Factory {
    MyClassWrapper create(MyClass myClass, Database db);
  }

  // ...

  @Inject
  private MyClassWrapper(@Assisted MyClass myClass, @Assisted Database db) {
    // ...
  }
}

Suppose I wanted to add another method signature to the MyClassWrapper.Factory interface:

List<MyClassWrapper> create(List<MyClass> myClass, Database db);

Can FactoryMethodBuilder figure out that I want to construct a list of MyClassWrapper objects from the list of MyClass objects? Or do I need to manually write the factory method implementation?


Solution

  • I don't think Guice supports this as a built-in, but you could write your own by injecting Providers of everything you need multiple of. (You didn't list any non-@Assisted dependencies; remember that you may not need to use Guice at all here.)

    You might also consider writing a static method that takes in your Factory and calls the Guice-created implementation on it, but you may lose in readability and comprehension what you gain in concise code.