Why do I have an error when I try to override a generic binding with Guice? (TypeLiteral)

前提是你 提交于 2019-12-10 03:26:44

问题


I'd like to override a generic type binding, but I allways got the same "No implementation was bound" error.

I'm using roboguice 3.

Here is a exemple of code that I use:

public interface IParser<I, O> {}

public class Parser1 implements IParser<String, String> {
    IParser<String, String> mParser;

    @Inject
    public Parser1(IParser<String, String> parser) {
        mParser = parser;
    }
}

public class Parser2 extends Parser1 {
    @Inject
    public Parser2(IParser<String, String> parser) {
        super(parser);
    }
}

public class MyModule extends AbstractModule {
    @Override
    protected void configure() {
        bind(new TypeLiteral<IParser<String, String>>() {}).to(new TypeLiteral<Parser1>() {});
    }
}

And here is my injector creation :

RoboGuice.getOrCreateBaseApplicationInjector(this,
                RoboGuice.DEFAULT_STAGE,
                RoboGuice.newDefaultRoboModule(this),
                Modules.override(new MyModule()).with(new AbstractModule() {
                    @Override
                    protected void configure() {
                        bind(new TypeLiteral<IParser<String, String>>() {}).to(new TypeLiteral<Parser2>() {});
                    }
                })
);

If I don't try to override it (only user Parser1), all is fine, when I override standard object with providers, it works well too, but not with TypeLiteral.

My error is :

com.google.inject.CreationException: Unable to create injector, see the following errors:
1) No implementation for IParser<String, String> was bound.

What am I doing wrong?

Thanks.


回答1:


You should change definition of classes which are implemented your interface.

Try this:

public class Parser1<I, O> implements IParser<I, O> {
}
public class Parser2<I, O> extends Parser1<I, O> {
}

And then you can bind your interface to class by this way:

bind(new TypeLiteral<IParser<String, String>>() {}).to(new TypeLiteral<Parser1<String, String>() {});



回答2:


I'm not shure, but it looks remarkable to me that a binding to a conrete instance is used instead to a Class:

bind(new TypeLiteral>() {}).to(new TypeLiteral() {});

did you try

bind(new TypeLiteral<IParser<String, String>>() {}).to(Parser2.class});

?



来源:https://stackoverflow.com/questions/34176461/why-do-i-have-an-error-when-i-try-to-override-a-generic-binding-with-guice-typ

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!