I've managed to list all subclasses of a given trait using knownDirectSubclasses() with scala-reflect. I'm not sure how to convert it to an instance of the object.
import scala.reflect.runtime.{universe => ru}
sealed trait Parent extends Product {
def toPrint: String = {
getClass.getSimpleName() + "!!!"
}
}
object UmbrellaObj {
case object Child1 extends Parent {}
case object Child2 extends Parent {}
implicit def toString(f: Parent): String = f.toPrint
}
val tpe = ru.typeOf[Parent]
val clazz = tpe.typeSymbol.asClass
println(UmbrellaObj.Child1.toString)
clazz.knownDirectSubclasses.foreach(x => {
println(x.toString)
})
In the above example, instead of x.toString(), I want to call member methods of the Child objects.
Aucun commentaire:
Enregistrer un commentaire