mardi 22 octobre 2019

How to dynamically construct subclass with parameters based on string

Code I have:

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

What I want: to instantiate a Cat or Dog dynamically.

I have made an attempt with code that looks like this:

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

It should dynamically instantiate the correct class using the animalType parameter. I think traditionally I would do this using a case statement (if animalType == "Cat", return new Cat(..)). But I believe there's an automatic way to do this with reflections.

The code doesn't compile. I've tried reading the Scala reflection docs but they don't have examples that show dynamic instantiation of subclasses with additional parameters





Aucun commentaire:

Enregistrer un commentaire