Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

reflection - Scala: set a field value reflectively from field name

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:

class Student {
    var id:Long
    var name:String
}

I need to create an instance of that class, in java i would get the Field by it's name and then do field.set(object, value) but I can't find how to do so in scala.

I can't use java reflection since the fields of Student are seen as private and field.set throws an error because of that.

Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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"

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...