mardi 9 février 2021

Scala reflection: get all constructor arguments of a specific type

I want to create a general purpose method def getOptionalArgs[T](): List[String] such that when passed a type, it returns the list of all arguments to that type that are an Option[_]

E.g. I have a case class Foo(bar: String, baz: Option[String]). In this case, getOptionalArgs[Foo]() would return List("baz").

I've been messing around with the reflections library, and I think I'm close via:

import scala.reflect.runtime.{universe, universe => ru}

def getOptionalArgs[T]() = {
 val constructor = ru.typeOf[T].decl(ru.termNames.CONSTRUCTOR).asMethod
 ...
}

But I cant figure out how map/filter the reflected constructors parameters. What is missing here?





Aucun commentaire:

Enregistrer un commentaire