简体   繁体   中英

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!

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)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM