Scala Reflections:在运行时按名称获取属性(classOf vs typeOf)

时间:2015-06-26 21:49:19

标签: scala reflection

Using scala 2.11.x

package reflections

import scala.reflect.ClassTag
import scala.reflect.runtime.universe._

object Reifier {

  def getPropertyList[T : TypeTag] =  {
    val smbls = typeOf[T].members map (m => m -> m.typeSignature) collect {
        case (m, nm: NullaryMethodType) => m
    }
    smbls map {_.name.toString}
  }.toList


  def getProperty[T : TypeTag](obj: T, property: String) = {
    val ru = scala.reflect.runtime.universe
    val m = runtimeMirror(ru.getClass.getClassLoader)
    val symb = ru.typeOf[T].decls(ru.TermName(property)).asTerm.accessed.asTerm
    val im = m.reflect(obj)
    val fld = im.reflectField(symb)
    fld.get
  }

}

目标是在运行时通过属性名称获取属性值。

 class P (val name: String)
 val p = new P("Marc")
 val n = Reifier.getProperty(p, "name")
 n should equal ("Marc")

ClassTag代替TypeTag

时,我不确定何时应使用classOf代替typeOf

0 个答案:

没有答案