I am looking at getting case class definitions.
From SO I gleaned this practice as per Get field names list from case class, the answer using reflection by Dia Kharrat.
Some experimenting in which I have a case class referring to another case class, nested. Can we get the metadata expanded easily in some way?
import scala.collection.mutable.ArrayBuffer
case class MyChgClass(b: Option[String], c: Option[String], d: Option[String])
case class MyFullClass(k: Int, b: String, c: String, d: String)
case class MyEndClass(id: Int, after: MyFullClass)
def classAccessors[T: TypeTag]: List[MethodSymbol] = typeOf[T].members.collect {
case m: MethodSymbol if m.isCaseAccessor => m
}.toList
val z1 = classAccessors[MyChgClass]
val z2 = classAccessors[MyFullClass]
val z3 = classAccessors[MyEndClass]
returns:
z1: List[reflect.runtime.universe.MethodSymbol] = List(value d, value c, value b)
z2: List[reflect.runtime.universe.MethodSymbol] = List(value d, value c, value b, value k)
z3: List[reflect.runtime.universe.MethodSymbol] = List(value after, value id)
So:
- Looking to expand the case class MyEndClass.
- The option aspect appears not not been supplied. Possible?
Are you looking for
.nameand.typeSignature?If your classes are known at compile time it would make sense to use compile-time reflection i.e. macros rather than runtime reflection
Even better would be to use one of libraries encapsulating those macros into some type classes. In Shapeless the type class giving access to names and types of case-class fields is
LabelledGenericYou can try deep versions of the type classes
LabelledGeneric,Mapperetc.Deriving nested shapeless lenses using only a type
Weird behavior trying to convert case classes to heterogeneous lists recursively with Shapeless
https://github.com/milessabin/shapeless/blob/main/examples/src/main/scala/shapeless/examples/deephlister.scala
Converting nested case classes to nested Maps using Shapeless
Automatically convert a case class to an extensible record in shapeless?