微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

scala – 如何使用反射评估懒惰的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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐