使用实验性的 Scala 2.10 反射,当我尝试在一个惰性 val 字段上调用 FieldMirror.get() 时,它返回 null。有没有办法使用反射来评估惰性验证?get() 函数之后不应再返回 null。
考虑这个例子:
case class Person(val firstName: String,
val lastName: String) {
lazy val name = firstName + " " + lastName
}
import scala.reflect.runtime.{universe => ru}
val runtimeMirror = ru.runtimeMirror(getClass.getClassLoader)
val fred = Person("Fred", "Smith")
val instanceMirror = runtimeMirror.reflect(fred)
val nameTerm = ru.typeOf[Person].declaration(ru.newTermName("name")).asTerm
val nameLazy = instanceMirror.reflectField(nameTerm)
nameLazy.get
>>> res8: Any = null
fred.name
>>> res9: String = Fred Smith
nameLazy.get
>>> res10: Any = Fred Smith