Monday, 19 August 2013

Google Guice - Use generic as parameter of injected field

Google Guice - Use generic as parameter of injected field

I want to use a generic parameter of a class for a field that is injected,
but guice complains about a unbound key. Is it possible to inject the
field in Test2?
Example:
public static class Test1<T1> {
}
public static class Test2<T2> {
@Inject
public Test1<T2> test;
}
public static void main(String[] args) throws Exception {
Injector injector = Jsr250.createInjector(Stage.PRODUCTION, new
TestModule());
Test2<String> test = injector.getInstance(Key.get(new
TypeLiteral<Test2<String>>(){}));
}
private static class TestModule extends AbstractModule {
@Override
protected void configure() {
bind(new TypeLiteral<Test1<String>>(){}).toInstance(new
Test1<String>());
bind(new TypeLiteral<Test2<String>>(){}).toInstance(new
Test2<String>());
}
}

No comments:

Post a Comment