Scala:如何按名称动态访问类属性?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28458881/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-22 06:55:07  来源:igfitidea点击:

Scala: How to access a class property dynamically by name?

scala

提问by jbrown

How can I look up the value of an object's property dynamically by name in Scala 2.10.x?

如何在 Scala 2.10.x 中按名称动态查找对象属性的值?

E.g. Given the class (it can't be a case class):

例如,给定类(它不能是案例类):

class Row(val click: Boolean,
          val date: String,
          val time: String)

I want to do something like:

我想做类似的事情:

val fields = List("click", "date", "time")
val row = new Row(click=true, date="2015-01-01", time="12:00:00")
fields.foreach(f => println(row.getProperty(f)))    // how to do this?

回答by Kamil Domański

class Row(val click: Boolean,
      val date: String,
      val time: String)

val row = new Row(click=true, date="2015-01-01", time="12:00:00")

row.getClass.getDeclaredFields foreach { f =>
 f.setAccessible(true)
 println(f.getName)
 println(f.get(row))
}

回答by Rich Henry

You could also use the bean functionality from java/scala:

您还可以使用 java/scala 中的 bean 功能:

import scala.beans.BeanProperty
import java.beans.Introspector

object BeanEx extends App { 
  case class Stuff(@BeanProperty val i: Int, @BeanProperty val j: String)
  val info = Introspector.getBeanInfo(classOf[Stuff])

  val instance = Stuff(10, "Hello")
  info.getPropertyDescriptors.map { p =>
    println(p.getReadMethod.invoke(instance))
  }
}