복붙노트

[SCALA] 스칼라 2.10 반사, 나는 경우 클래스의 경우 클래스, 즉 필드 목록에서 필드 값을 추출 어떻게

SCALA

스칼라 2.10 반사, 나는 경우 클래스의 경우 클래스, 즉 필드 목록에서 필드 값을 추출 어떻게

어떻게 스칼라 2.10의 새로운 반사 모델을 사용하여 스칼라의 경우 클래스의 필드 값을 추출 할 수 있습니다? 예를 들어, 아래 사용하는 필드 방법을 당겨하지 않습니다

  def getMethods[T:TypeTag](t:T) =  typeOf[T].members.collect {
    case m:MethodSymbol => m
  }

나는 그들을 펌프 계획

  for {field <- fields} {
    currentMirror.reflect(caseClass).reflectField(field).get
  }

해결법

  1. ==============================

    1.MethodSymbol은 정확하게이 작업을 수행 할 수있는 isCaseAccessor 방법이 있습니다 :

    MethodSymbol은 정확하게이 작업을 수행 할 수있는 isCaseAccessor 방법이 있습니다 :

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

    이제 다음을 작성할 수 있습니다 :

    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)
    

    그리고 당신은 당신이 원하는 유일한 방법 기호를 얻을.

    그냥 실제 필드 이름 (값 접두사를) 원하는 경우에 당신은 다음 같은 순서로 원하는 :

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

    2.당신은 애호가 얻고 싶은 경우에 당신은 생성자 기호를 검사하여 순서대로 얻을 수 있습니다. 이 코드는 문제의 경우 클래스 유형이 여러 생성자가 정의 된 경우에도 작동합니다.

    당신은 애호가 얻고 싶은 경우에 당신은 생성자 기호를 검사하여 순서대로 얻을 수 있습니다. 이 코드는 문제의 경우 클래스 유형이 여러 생성자가 정의 된 경우에도 작동합니다.

      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
        }
      }
    
  3. from https://stackoverflow.com/questions/16079113/scala-2-10-reflection-how-do-i-extract-the-field-values-from-a-case-class-i-e by cc-by-sa and MIT license