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

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

提交回复
热议问题