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