【问题标题】:Why do I have an error when I try to override a generic binding with Guice? (TypeLiteral)当我尝试使用 Guice 覆盖泛型绑定时,为什么会出现错误? (类型文字)
【发布时间】:2015-12-09 10:28:44
【问题描述】:

我想重写泛型类型绑定,但总是遇到相同的“No implementation was bound”错误。

我正在使用 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>() {});
    }
}

这是我创建的注射器:

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.

我做错了什么?

谢谢。

【问题讨论】:

  • 有人知道吗? Aurélien 需要提供更多信息吗?
  • 我无法在 Guice 4 下重现这种行为。我会注意到存在循环依赖关系,Guice 使用代理类 shim 来满足这种依赖关系。 Roboguice 会在某处禁用代理吗?
  • 旁注:你永远不需要new TypeLiteral&lt;ASimpleType&gt;() {},你可以使用ASimpleType.class

标签: java android generics guice


【解决方案1】:

您应该更改实现您的接口的类的定义。

试试这个:

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

然后你可以通过这种方式将你的接口绑定到类:

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

【讨论】:

  • 它不应该在实现类上要求类型参数,添加它们不会影响 Guice 如何处理绑定。
  • 在这种情况下,您将得到“我”无法解析为您的答案第一行中的类型。这甚至无法编译。
【解决方案2】:

我不是 shure,但在我看来,一个对具体实例的绑定被用来代替 Class

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

你试过了吗

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

?

【讨论】:

  • 绑定到类型文字实例相当于绑定到类。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-09-07
  • 1970-01-01
  • 2021-09-13
  • 2012-08-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多