【问题标题】:Scala Dependency injection with generic classScala 依赖注入与泛型类
【发布时间】:2018-07-23 19:09:45
【问题描述】:

在 Scala 中使用 Guice,我正在尝试重现以下 Java 代码。

Foo接口和类声明:

public interface Foo[T] {}
public class FooImpl[T] implements Foo[T] {}

Guice绑定代码:

bind(Foo.class).to(FooImpl.class);

一个使用示例是;

@Inject
public class Bar(Foo<String> foo) {}

在 scala 中,我的第一个赌注是:

bind(classOf[Foo]).to(classOf[FooImpl])

但它在抱怨“Type Foo 接受类型参数” 我如何在 scala 中实现这一点?

谢谢

【问题讨论】:

  • bind(classOf[Foo&lt;String&gt;]).to(classOf[FooImpl&lt;String&gt;])怎么样
  • bind(classOf[Foo[_]]).to(classOf[FooImpl[_]])
  • 您好 Dima,感谢您的回答。看起来它正在工作,但我现在无法确认,因为我面临另一个问题。我的班级有 2 个隐式参数,看起来它们没有使用 Guice 和注入正确提供。如果它确实有效,我会通知你,以便你用它来回答我的问题。

标签: java scala dependency-injection guice


【解决方案1】:

您的问题有错误,因此您可以得到错误的答案。

让我们首先修正你的概念想法。有trait

trait Foo[T] { def hello: T }

工作得很好。但是,扩展此特征的特定类将是,f.e.:

class FooImpl1 extends Foo[Int] { override def hello: Int = 42 }
class FooImpl2 extends Foo[String]{ override def hello: String = "test" }

他们不可能是:

class FooImpl[Int] extends Foo[Int] { override def hello: Int = 42 }
class FooImpl[String] extends Foo[String]{ override def hello: String = "test" }

因为那时,IntString 只是通用参数的 NAME。也可以是AB,但是你自己弄糊涂了。


解决了这个问题,你知道你有FooImpl1FooImpl2。 它们需要不同的名称,因为在同一范围内不能有两个名称相同的类!

而且很好。因为当你:

bind(classOf[X]).to(classOf[Y])

您是说,每当您的类调用InterfaceTrait X 的方法时,您希望提供类Y 的实现。

必须提供一个可以实例化的类!你不能用泛型参数实例化一个类。

最后,您的正确绑定应如下所示:

bind(new TypeLiteral[Foo[Int]](){}).to(classOf[FooImpl1])
bind(new TypeLiteral[Foo[String]](){}).to(classOf[FooImpl2])

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-29
    • 1970-01-01
    • 1970-01-01
    • 2020-03-25
    • 1970-01-01
    相关资源
    最近更新 更多