2

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>());
        }
    }
4

1 回答 1

0

好吧,这对于 java 泛型来说是多余的。即使没有注入,您的代码也无法工作,因为Test1<T2>无法匹配Test1<String>。您应该考虑不同的方法,尝试使用Annotation 绑定,例如:

public static class Test2 {
        @Inject @Named("T2")
        public Test1<someGenericInterface> test;
    }

bind(new TypeLiteral<Test1<someGenericInterface>>(){}).annotatedWith(Names.named("T2")).toInstance(new Test1<T2>()); //T2 implements someGenericInterface
bind(new TypeLiteral<Test1<someGenericInterface>>(){}).annotatedWith(Names.named("T1")).toInstance(new Test1<T1>()); //T1 implements someGenericInterface

或实现特定的 Provider Provider 绑定或使用MapBinder

于 2013-08-21T10:26:27.457 回答