Scala: set a field value reflectively from field name

前端 未结 1 1270
情歌与酒
情歌与酒 2020-12-13 01:01

I\'m learning scala and can\'t find out how to do this:

I\'m doing a mapper between scala objects and google appengine entities, so if i have a class like this:

相关标签:
1条回答
  • 2020-12-13 01:32

    Scala turns "var" into a private field, one getter and one setter. So in order to get/set a var by identifying it using a String, you need to use Java reflection to find the getter/setter methods. Below is a code snippet that does that. Please note this code runs under Scala 2.8.0 and handlings of duplicated method names and errors are nonexistent.

    class Student {
      var id: Long = _
      var name: String = _
    }
    
    implicit def reflector(ref: AnyRef) = new {
      def getV(name: String): Any = ref.getClass.getMethods.find(_.getName == name).get.invoke(ref)
      def setV(name: String, value: Any): Unit = ref.getClass.getMethods.find(_.getName == name + "_$eq").get.invoke(ref, value.asInstanceOf[AnyRef])
    }
    
    val s = new Student
    s.setV("name", "Walter")
    println(s.getV("name"))  // prints "Walter"
    s.setV("id", 1234)
    println(s.getV("id"))    // prints "1234"
    
    0 讨论(0)
提交回复
热议问题