首页 > 解决方案 > 用于 kotlin 集合的 Guice Typeliteral(例如 kotlin.collections.Iterable)搜索 java.lang.Iterable

问题描述

问题

在 kotlin 中,为 guice 配置以下模块

fun configureFoo(binder: Binder) {
  binder.bind(object: TypeLiteral<Foo<Iterable<Any>>>() {}).to(MyFoo::class.java)
}

和示例类

interface Foo<T> {
  // ...
}

class MyFoo : Foo<Iterable<Any>> {
  // ...
}

class User @Inject constructor(foo: Foo<Iterable<Any>>) {
  // ...
}

我得到 guice 配置错误:

No implementation for Foo<java.lang.Iterable<Any>> was bound. ...

我试过的

我可以通过更改Iterablejava.lang.Iterable任何地方来解决这个问题......但这是一个糟糕的解决方法,失去了kotlin.collections.Iterable.

问题

有谁知道这个问题并有更好的解决方案?

标签: javakotlindependency-injectionguice

解决方案


简单的解决方法,直到出现更好的解决方案

现在我正在使用如下解决方法,以防有人偶然发现该问题:

我定义了专门MultiFoo<Any>的 s 并使用它们,而不是Foo<Iterable<Any>>每当我想为 Foo 使用可迭代的类型参数时:

fun configureFoo(binder: Binder) {
  // bind an iterable Any for Foo
  binder.bind(object: TypeLiteral<MultiFoo<Any>>() {}).to(MyFoo::class.java)

  // bind a single Any For Foo
  binder.bind(object: TypeLiteral<Foo<Any>>() {}).to(MySingleFoo::class.java)
}
interface Foo<T> {
  // ...
}
interface MultiFoo<T>: Foo<Iterable<T>> {
  // ...
}

class MyFoo : MultiFoo<Any> {
  // ...
}

class MySingleFoo : Foo<Any> {
  // ...
}
class User @Inject constructor(foo: MultiFoo<Any>, bar: Foo<Any>) {
  // ...
}

虽然为注入绑定和构造函数参数创建和使用额外的类不是很漂亮,但至少注入的类遵守所需的接口契约......我可以MultiFoo<Any>用作Foo<Iterable<Any>>


推荐阅读