如何使用反射评估懒惰的val?

时间:2013-05-03 14:28:24

标签: scala reflection lazy-evaluation

使用实验性的Scala 2.10反射,当我尝试在一个惰性val的字段上调用FieldMirror.get()时,它返回null。有没有办法用反射评估懒惰的val?之后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

1 个答案:

答案 0 :(得分:6)

我发现了解决方案。有一个隐藏的方法生成:

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 nameMethod = ru.typeOf[Person].member(ru.newTermName("name")).asMethod
val nameValue = ru.typeOf[Person].member(ru.newTermName("name")).asTerm

val nameLazy = instanceMirror.reflectField(nameValue)
val nameLazyMethod = instanceMirror.reflectMethod(nameMethod)

nameLazy.get
    >>> null

nameLazyMethod()
    >>> res9: String = Fred Smith

nameLazy.get
    >>> res10: String = Fred Smith