Guice

时间:2015-08-04 18:14:45

标签: scala guice

在我的Scala项目中,我使用Guice来绑定出现在三元组中的许多类,如:

bind[Foo1Component].to[Foo1]
bind[Foo2Component].to[Foo2]
bind[Foo3Component].to[Foo3]
// And so on for Bar, Baz, etc.

我认为有一个函数可以传递字符串"Foo"并让它完成所有三个绑定。我能得到的最接近的是:

def bindAll(name: String): Unit = {
  bind(Class.forName(name + "1Component")).to(Class.forName(name + "1"))
  // likewise for 2 and 3, or do it in a loop
}

...但是这给了我一个冗长的错误消息,结果是编译器无法找出我想要的重载to方法。由于bind(classOf[Foo1Component]).to(classOf[Foo1])有效,我认为问题是Class.forName会返回Class[_]而不是Class,并带有适当的类型参数。

有没有办法像这样动态绑定类?

0 个答案:

没有答案
相关问题