mardi 22 février 2022

How do I fetch the override member of a sealed trait via reflection?

I'm trying to write a generalised function that takes a Type of SomeSealedClass and uses reflection to return a list of values overridden by the trait's child classes/objects.

sealed abstract class Sealed(val name: String)
object Sealed {
    case object One extends Sealed("first one")
    case object Two extends Sealed("second one")
    case object Three extends Sealed("third one")
}

def expand(sealed: Type): List[String] = ???

I need the function expand to return List("first one", "second one", "third one") but only if Sealed has a field called name.

I don't have access to the type because the caller is building the type object from a string using Class.forName(). So, I cannot create instance mirrors to fetch the value of the name field from each of the subclasses.

I'm starting to think that this is not actually possible but cannot figure out why. Those values are fixed. So, it should be simple to extract them without the type, isn't it?





Aucun commentaire:

Enregistrer un commentaire