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

后端 未结 2 1113
小蘑菇
小蘑菇 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))
    }
    

提交回复
热议问题