简体   繁体   English

Scala使用Class创建实例,该实例接受鸭子的输入参数

[英]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. 我有val classInstance: Class[A]对象。 I want to instantiate this class instance with parameter indicated in the ducktype above. 我想用上面的ducktype中指定的参数实例化该类实例。 How do I do this in Scala. 我如何在Scala中做到这一点。

In Java you could get constructor with the dependency. 在Java中,您可以获得具有依赖项的构造函数。 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)
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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