Java 带有泛型类的Scala依赖项注入
使用Scala中的Guice,我试图重现以下Java代码 Foo接口和类声明:Java 带有泛型类的Scala依赖项注入,java,scala,dependency-injection,guice,Java,Scala,Dependency Injection,Guice,使用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) {} 但它抱怨“类型Foo接受类型参数” 如何在scala中实现这
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) {}
但它抱怨“类型Foo接受类型参数”
如何在scala中实现这一点
谢谢您的问题有错误,因此允许您给出错误答案。 让我们首先修正您的概念想法。具有
特征的
trait Foo[T] { def hello: T }
很好用。但是,扩展这一特性的特定类别将是,例如:
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" }
因为这样,Int
或String
只是泛型参数的名称。它也可以是A
和B
,但你只是把自己弄糊涂了
解决了这个问题后,您知道您有
FooImpl1
和FooImpl2
。
它们需要不同的名称,因为在同一范围内不能有两个名称相同的类
而且很好。因为当你:
bind(classOf[X]).to(classOf[Y])
您告诉我们,无论何时您的类调用接口
或Trait
X
的方法,您都希望提供类Y
的实现
必须提供一个可以实例化的类!无法使用泛型参数实例化类
最后,您的正确绑定如下所示:
bind(new TypeLiteral[Foo[Int]](){}).to(classOf[FooImpl1])
bind(new TypeLiteral[Foo[String]](){}).to(classOf[FooImpl2])
您的问题有错误,因此允许您给出错误答案。 让我们首先修正您的概念想法。具有
特征的
trait Foo[T] { def hello: T }
很好用。但是,扩展这一特性的特定类别将是,例如:
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" }
因为这样,Int
或String
只是泛型参数的名称。它也可以是A
和B
,但你只是把自己弄糊涂了
解决了这个问题后,您知道您有
FooImpl1
和FooImpl2
。
它们需要不同的名称,因为在同一范围内不能有两个名称相同的类
而且很好。因为当你:
bind(classOf[X]).to(classOf[Y])
您告诉我们,无论何时您的类调用接口
或Trait
X
的方法,您都希望提供类Y
的实现
必须提供一个可以实例化的类!无法使用泛型参数实例化类
最后,您的正确绑定如下所示:
bind(new TypeLiteral[Foo[Int]](){}).to(classOf[FooImpl1])
bind(new TypeLiteral[Foo[String]](){}).to(classOf[FooImpl2])
如何
bind(classOf[Foo])。to(classOf[FooImpl])
bind(classOf[Foo[\u]])。to(classOf[FooImpl[\u]])
你好,谢谢你的回答。它看起来很有效,但我现在无法确认,因为我面临另一个问题。我的类中有两个隐式参数,看起来它们没有使用Guice和injection正确提供。如果它真的有效,我会让你知道,这样你就可以用它来回答我的问题。关于bind(classOf[Foo])。to(classOf[FooImpl])
bind(classOf[Foo[\u]])。to(classOf[FooImpl[\u]])
Hi Dima,谢谢你的回答。它看起来很有效,但我现在无法确认,因为我面临另一个问题。我的类中有两个隐式参数,看起来它们没有使用Guice和injection正确提供。如果它真的有效,我会让你知道,这样你就可以用它回答我的问题。