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

前端 未结 2 457
生来不讨喜
生来不讨喜 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:07

    MethodSymbol has an isCaseAccessor method that allows you to do precisely this:

    def getMethods[T: TypeTag] = typeOf[T].members.collect {
      case m: MethodSymbol if m.isCaseAccessor => m
    }.toList
    

    Now you can write the following:

    scala> case class Person(name: String, age: Int)
    defined class Person
    
    scala> getMethods[Person]
    res1: List[reflect.runtime.universe.MethodSymbol] = List(value age, value name)
    

    And you get only the method symbols you want.

    If you just want the actual field name (not the value prefix) and you want them in the same order then:

    def getMethods[T: TypeTag]: List[String] =
      typeOf[T].members.sorted.collect {
        case m: MethodSymbol if m.isCaseAccessor => m.name.toString
      }
    

提交回复
热议问题