user_1357
user_1357

Reputation: 7940

Scala create instance with Class which accepts duck typing parameter

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

Answers (1)

Lee
Lee

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

Related Questions