scala - Scala: How to create a class method which return class variable value by taking variable name as string input
问题描述
I'm new to Scala, and I'm trying to write a class method in Scala which takes the class variable name (as string) as input and returns that variable value. Say I have a class Person
with variables name
and age
.
I need a method getVar
in class Person
which can do
//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"
I don't know how do I refer to that class variable by name in getVar
method. Any help would be appreciated
解决方案
You can use 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
}
推荐阅读
- javascript - 如果机器人被 ping 通
- c++ - 使用指向内联函数的指针与使用指向函数的指针
- kubernetes - 同一节点上运行的 Pod 不能通过 service 相互访问
- php - 如何强制 imap_open 和 PHPMailer 使用指定的替代网络接口或 SOCKS 代理?
- r - 识别分组变量的唯一值
- python - pipenv 安装后出现“ModuleNotFoundError: No module named 'yaml'”
- php - Podio API PHP 更新项目关系类型。什么时候为空不起作用
- html - 使用 position: absolute 垂直对齐顶部导航项
- excel - 从excel文档中提取数据
- html - 为什么文本在一个
tag smaller, but only sometimes?