如何根据字符串动态构造带参数的子类

How to dynamically construct subclass with parameters based on string

我有代码:

abstract class Animal {
   def init(animalType: String, jsonBlob: String)
}

class Dog (name: String, colour: String) {
   def init(animalType: String, jsonBlob: String) : Unit = {
        name = jsonBlob.name
        colour = jsonBlob.colour
    }
}

class Cat (address: String) {
   def init(animalType: String, jsonBlob: String) : Unit = {
        address = jsonBlob.address
    }
}

我想要的是:动态实例化猫或狗。

我尝试使用如下代码:

case class AnimalDefinition(animalType: String, jsonBlob: String)
val animalDefinitions : Array[AnimalDefinition] = // 
val animals : Array[Animal] = animalDefinitions.map(new Animal(_.animalType, _.jsonBlob)) 

它应该使用 animalType 参数动态实例化正确的 class。我认为传统上我会使用 case 语句 (if animalType == "Cat", return new Cat(..)) 来做到这一点。但我相信有一种自动的方法可以通过反射来做到这一点。

代码无法编译。我试过阅读 Scala 反射文档,但他们没有示例显示带有附加参数

的 subclasses 的动态实例化

你可以替换

if animalType == "Cat", return new Cat("cat name") ...

import scala.reflect.runtime.universe._
val mirror = runtimeMirror(getClass.getClassLoader)
val classSymbol = mirror.staticClass(animalType)
val typ = classSymbol.info
val constructorSymbol = typ.decl(termNames.CONSTRUCTOR).asMethod
val classMirror = mirror.reflectClass(classSymbol)
val constructorMirror = classMirror.reflectConstructor(constructorSymbol)
constructorMirror("cat name").asInstanceOf[Animal]