我想覆盖泛型类型绑定(bind),但我总是遇到相同的“未绑定(bind)实现
”错误。
我正在使用 roboguice 3。
这是我使用的代码示例:
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>() {});
}
}
这是我创建的注入(inject)器:
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>() {});
}
})
);
如果我不尝试覆盖它(仅用户 Parser1),一切都很好,当我用提供者覆盖标准对象时,它也能正常工作,但不适用于 TypeLiteral。
我的错误是:
com.google.inject.CreationException: Unable to create injector, see the following errors:
1) No implementation for IParser<String, String> was bound.
我做错了什么?
谢谢。
最佳答案
您应该更改实现了您的接口(interface)的类的定义。
试试这个:
public class Parser1<I, O> implements IParser<I, O> {
}
public class Parser2<I, O> extends Parser1<I, O> {
}
然后你可以通过这种方式将你的接口(interface)绑定(bind)到类:
bind(new TypeLiteral<IParser<String, String>>() {}).to(new TypeLiteral<Parser1<String, String>() {});
关于java - 当我尝试使用 Guice 覆盖通用绑定(bind)时,为什么会出现错误? (文字类型),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34176461/