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

后端 未结 2 1111
小蘑菇
小蘑菇 2021-02-13 09:33

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

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

class Row(val         


        
相关标签:
2条回答
  • 2021-02-13 09:56
    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))
    }
    
    0 讨论(0)
  • 2021-02-13 10:16

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

    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))
      }
    }
    
    0 讨论(0)
提交回复
热议问题