vendredi 26 juin 2015

get property by name at runtime

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 property value by property name at runtime.

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

I am unsure when TypeTag should be used instead of ClassTag, when typeOf instead of classOf





Aucun commentaire:

Enregistrer un commentaire