Suppose I have a third party class as follows:
public class MyObject { @Inject public MyObject(Foo foo, Bar bar) { ... } }
Now suppose I have a factory interface, for example:
public interface MyObjectFactory { public MyObject build(Bar bar); }
The idea is that I want to have a MyObjectFactory that builds MyObject for a fixed Foo - that is, essentially adding a @Assisted annotation to the Bar constructor parameter from the outside. Of course, manually implementing MyObjectFactory is always possible:
public class MyObjectFactoryImpl implements MyObjectFactory { @Inject private Provider<Foo> foo; @Override public MyObject build(Bar bar) { return new MyObject(foo.get(), bar); } }
But let's say that there are conditions that require that I have instances of Guice build MyObject - for example, method hooks. This seems to work for an “injector injection":
public class MyObjectFactoryImpl implements MyObjectFactory { @Inject private Injector injector; @Override public MyObject build(Bar bar) { Injector child = injector.createChildInjector(new AbstractModule() { @Override protected void configure() { bind(Bar.class).toInstance(bar);
It sounds wicked and boiler-tiled-y, so I'm wondering if there are alternative implementations and / or a way to get Guice to generate a factory impl.
source share