In my Scala project, I use Guice to bind a number of classes that occur in triples, something like:
bind[Foo1Component].to[Foo1]
bind[Foo2Component].to[Foo2]
bind[Foo3Component].to[Foo3]
// And so on for Bar, Baz, etc.
I thought it would be nice to have a function to which I pass the string "Foo"
and have it do all three bindings. The closest I've been able to get is:
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
}
...but this gives me a lengthy error message to the effect that the compiler can't figure out which overloaded to
method I want. Since bind(classOf[Foo1Component]).to(classOf[Foo1])
works, I suppose the issue is that Class.forName
returns a Class[_]
rather than a Class
with an appropriate type parameter.
Is there any way to bind classes dynamically like this?