我发现了其他相关问题,但没有一个如此简单:
如何使用Guice绑定以下通用参数?
class A<T> {
T a;
@Inject A(T a) {
this.a=a;
}
}
答案 0 :(得分:3)
public class TestGenericBinding {
static class A<T> {
T a;
@Inject A(T a) {
this.a=a;
}
}
@Test public void bindingWorked() {
Injector injector = Guice.createInjector(new AbstractModule() {
@Override
protected void configure() {
bind(Integer.class).toInstance(123);
bind(new TypeLiteral<A<Integer>>() {});
}
});
A<Integer> a = injector.getInstance(
Key.get(new TypeLiteral<A<Integer>>(){}));
assertEquals(new Integer(123),a.a);
}
}