How to access a field's value via reflection (Scala 2.8)

前端 未结 5 2063
北海茫月
北海茫月 2021-02-08 00:18

Consider the following code:

class Foo(var name: String = \"bar\")

Now i try to get the value and the correct type of it via reflection:

<
5条回答
  •  自闭症患者
    2021-02-08 00:43

    This is how one can get list of fieldnames and its value of a case class:
    First, using reflection, get fields info as follows -

    val TUPLE2_OF_FIELDNAME_TO_GETTERS = typeOf[].members
    .filter(!_.isMethod)
    .map(x => (x.name.toString, classOf[].getDeclaredMethod(x.name.toString.trim)))
    

    How to use it?

    getFieldNameAndValue(obj: ): Seq[(String, String)] {
      var output = Seq[(String, String)]()
     for(fieldToGetter <- TUPLE2_OF_FIELDNAME_TO_GETTERS) {
          val fieldNameAsString = fieldToGetter._1
          val getter = fieldToGetter._2
          val fieldValue = getter.invoke(obj).toString
          output += (fieldName, fieldValue)
        }
    }
    

提交回复
热议问题