我有以下代码:
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参数动态实例化正确的类。我认为传统上我会使用case语句(if animalType == "Cat", return new Cat(..))
来做这件事。但我相信有一种自动的方法可以通过反射来做到这一点。
代码不能编译。我尝试过阅读Scala反射文档,但它们没有显示带有附加参数的子类的动态实例化的示例
发布于 2019-10-25 11:45:56
你可以替换
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]
https://stackoverflow.com/questions/58513977
复制相似问题