Scala:如何创建通过将变量名称作为字符串输入来返回类变量值的类方法

时间:2019-02-20 10:32:43

标签: scala class

我是Scala的新手,我试图在Scala中编写一个类方法,该方法将类变量名(作为字符串)作为输入并返回该变量值。假设我有一个类Person,其中包含变量nameage

我需要类getVar中的方法Person可以做到

//Expected output in comments next to a method call

val p1 = new Person(name="abc",age=23);
p1.getVar("age"); //Returns 23
p1.getVar("name"); //Returns "abc" 

我不知道如何在getVar方法中按名称引用该类变量。任何帮助将不胜感激

1 个答案:

答案 0 :(得分:1)

您可以使用reflection

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

abstract class FieldRequestSupport[SelfType <: Product : ClassTag : TypeTag] {
    self: SelfType =>

    private val classFieldsAccessors: Map[String, MethodSymbol] = typeOf[SelfType].members.collect({
        case m: MethodSymbol if m.isCaseAccessor => m
    }).flatMap(symbol => TermName.unapply(symbol.name).map((_, symbol)))(collection.breakOut)
    private val classMirror: Mirror = runtimeMirror(getClass.getClassLoader)

    def requestField(fieldName: String): Option[Any] = {
        classFieldsAccessors.get(fieldName).map(
            symbol => classMirror.reflect(self).reflectField(symbol).get
        )
    }
}

case class Person(name: String, age: Int) extends FieldRequestSupport[Person]

object Test extends App {
    val person = Person("Bob", 26)
    println(person.requestField("name")) //will print Some(Bob)
    println(person.requestField("age")) //will print Some(26)
    println(person.requestField("qqq")) //will print None
}