如何使用反射来计算一个lazy val



使用实验性的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

我找到了解决方案。生成了一个隐藏方法:

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

相关内容

  • 没有找到相关文章

最新更新