Scala Reflections: getting a property by name at runtime (classOf vs typeOf)

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
  }

}

The goal is to get the value of a property by the name of the property at runtime.

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

I'm not sure when ClassTagto use instead TypeTag, if typeOfinsteadclassOf

+4
source share

All Articles