Reputation: 7940
I have following class:
class Test(env: {val configConsumner: ConfigurationConsumer})
And I have val classInstance: Class[A]
object. I want to instantiate this class instance with parameter indicated in the ducktype above. How do I do this in Scala.
In Java you could get constructor with the dependency. Then instantiate that constructor with the parameter using reflection.
Thanks!
Upvotes: 2
Views: 652
Reputation: 144136
Assuming the type's constructor has no arguments you can do:
def createTest[A <: {val configConsumner: ConfigurationConsumer}](c: Class[A]): Test = new Test(c.newInstance())
if the constructor does have arguments you can use:
def createTest[A <: {val configConsumner: ConfigurationConsumer}](c: Class[A], args: Any*): Test = {
val constructor = c.getConstructor(args.map(_.getClass) : _*)
val inst = constructor.newInstance(args.toArray : _*)
new Test(inst)
}
Upvotes: 4