Scala 2.10 reflection, how do I extract the field values from a case class, i.e. field list from case class

前端 未结 2 453
生来不讨喜
生来不讨喜 2020-12-02 15:31

How can I extract the field values from a case class in scala using the new reflection model in scala 2.10? For example, using the below doesn\'t pull out the field methods<

2条回答
  •  隐瞒了意图╮
    2020-12-02 16:24

    If you want to get fancier you can get them in order by inspecting the constructor symbol. This code works even if the case class type in question has multiple constructors defined.

      import scala.collection.immutable.ListMap
      import scala.reflect.runtime.universe._
    
      /**
        * Returns a map from formal parameter names to types, containing one
        * mapping for each constructor argument.  The resulting map (a ListMap)
        * preserves the order of the primary constructor's parameter list.
        */
      def caseClassParamsOf[T: TypeTag]: ListMap[String, Type] = {
        val tpe = typeOf[T]
        val constructorSymbol = tpe.decl(termNames.CONSTRUCTOR)
        val defaultConstructor =
          if (constructorSymbol.isMethod) constructorSymbol.asMethod
          else {
            val ctors = constructorSymbol.asTerm.alternatives
            ctors.map(_.asMethod).find(_.isPrimaryConstructor).get
          }
    
        ListMap[String, Type]() ++ defaultConstructor.paramLists.reduceLeft(_ ++ _).map {
          sym => sym.name.toString -> tpe.member(sym.name).asMethod.returnType
        }
      }
    

提交回复
热议问题