samedi 23 mai 2020

Dynamically instantiate a class based on that classes name, in Scala

I have a group of classes, each of which has a member called Description.
I would like the end-user of my library to be able to specify which classes they are interested and be able to read that description. Hence I want to be able to dynamically instantiate each of the specified classes and return the Description.

I'm aware that I need reflection to do this and I've seen a lot of SO questions suggesting Class.forName can help me but I haven't been able to get it working.

Hopefully the following demonstrates what I want to be able to do:

scala> abstract class Feature (start: Short, end: Short){val description: String}
defined class Feature

scala> class Feature1 (start: Short, end: Short) extends Feature(start, end){override val description = "this is feature 3"}
defined class Feature1

scala> class Feature2 (start: Short, end: Short) extends Feature(start, end){override val description = "this is feature 2"}
defined class Feature2

scala> class Feature3 (start: Short, end: Short) extends Feature(start, end){override val description = "this is feature 3"}
defined class Feature3

scala> val classesForWhichIWantToGetTheDescription = Set[String]("Feature1", "Feature2")
classesForWhichIWantToGetTheDescription: scala.collection.immutable.Set[String] = Set(Feature1, Feature2)

scala> val classesWithDescriptions = classesForWhichIWantToGetTheDescription.map(
     |     className => (className, s"I want the class description of ${className} to be displayed here")
     | )
classesWithDescriptions: scala.collection.immutable.Set[(String, String)] = Set((Feature1,I want the class description of Feature1 to be displayed here), (Feature2,I want the class description of Feature2 to be displayed here))

scala> classesWithDescriptions.foreach(
     |     c => println(c)
     | )
(Feature1,I want the class description of Feature1 to be displayed here)
(Feature2,I want the class description of Feature2 to be displayed here)

Can anyone help me achieve this?

thanks in advance





Aucun commentaire:

Enregistrer un commentaire