Scala:从字段名称反射设置字段值 [英] Scala: set a field value reflectively from field name
问题描述
我正在学习 Scala,但不知道如何做到这一点:
I'm learning scala and can't find out how to do this:
我正在 scala 对象和 google appengine 实体之间做一个映射器,所以如果我有一个这样的类:
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
}
我需要创建该类的一个实例,在java中我会通过它的名字来获取字段,然后执行 field.set(object, value)
但我找不到怎么做所以在 Scala 中.
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.
我不能使用 Java 反射,因为 Student 的字段被视为私有字段,因此 field.set 会抛出错误.
I can't use java reflection since the fields of Student are seen as private and field.set throws an error because of that.
谢谢
推荐答案
Scala 将var"变成了一个私有字段,一个 getter 和一个 setter.因此,为了通过使用字符串识别 var 来获取/设置 var,您需要使用 Java 反射来查找 getter/setter 方法.下面是执行此操作的代码片段.请注意,此代码在 Scala 2.8.0 下运行,不存在重复方法名称和错误的处理.
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"
这篇关于Scala:从字段名称反射设置字段值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!