The following code is an example of a factory that produces a Bar
given a Foo
. The factory doesn't care what T
is: for any type T
, it can make a Bar
from a Foo
.
import com.google.inject.*; import com.google.inject.assistedinject.*; class Foo { public void flip(T x) { System.out.println("flip: " + x); } } interface Bar { void flipflop(T x); } class BarImpl implements Bar { Foo foo; @Inject BarImpl(Foo foo) { this.foo = foo; } public void flipflop(T x) { foo.flip(x); System.out.println("flop: " + x); } } interface BarFactory { Bar create(Foo f); } class Module extends AbstractModule { public void configure() { bind(BarFactory.class) .toProvider( FactoryProvider.newFactory( BarFactory.class, BarImpl.class ) ); } } public class GenericInject { public static void main(String[] args) { Injector injector = Guice.createInjector(new Module()); Foo foo = new Foo(); Bar bar = injector.getInstance(BarFactory.class).create(foo); bar.flipflop(0); } }
When I run the code, I get the following errors from Guice:
1) No implementation for BarFactory was bound. at Module.configure(GenericInject.java:38) 2) Bar cannot be used as a key; It is not fully specified.
The only reference I can find to generics in the Guice documentation says to use a TypeLiteral
. But I don't have a literal type, I have a generic placeholder that isn't relevant to the factory at all. Any tips?