在Scala中动态访问类变量

时间:2018-08-10 17:32:03

标签: scala functional-programming scala-collections

我有一个scala类,其中包含各种变量,如下所示:

class Square { 
 var x: Double = 0
 var y: Double = 0
 var width: Double = 0
 var height: Double = 0
 def area(): Double = width * height
}

我在其他文件中创建类的所有成员的列表,如下所示:

val res26= List("x","y","height","width")

我想从其他文件访问这些变量,如下所示:

val test= res26.map(t=>(t,s1.t)).toMap which throws below error:

error: value t is not a member of Square
val test= res26.map(t=>(t,s1.t)).toMap

反正我可以动态访问变量吗?

1 个答案:

答案 0 :(得分:0)

您可以使用java reflection instance.getClass.getDeclaredMethod(methodName).invoke(instance)

object TestJavaReflection {

  def main(args: Array[String]): Unit = {

    case class Square(x: Double = 0, y: Double = 0, width: Double = 0, height: Double = 0) {
      def area(): Double = width * height
    }

    val myInstance = Square(1.0, 2.0, 3.0, 4.0)

    val fields = List("x", "y", "height", "width")

    val data = fields.map(fieldName => fieldName -> myInstance.getClass.getDeclaredMethod(fieldName).invoke(myInstance))
                     .toMap

    println(data)
  }

}

您得到的结果是:

Map(x -> 1.0, y -> 2.0, height -> 4.0, width -> 3.0)