获取对象中变量的名称

时间:2015-11-21 00:54:44

标签: scala

考虑以下object

class sampleClass { 
  val firstname = "hassan" 
  val lastname = "kachal"
} 

def anotherFunction() { 
   val sampleObj = new sampleClass()
   // here print the list of variables in "sampleObj"
   // I expect to see "firstName" and "lastName" in the output 
}

如何在对象中打印变量的名称? (比如在对象sampleObj中,我需要在输出中打印firstNamelastName)。

1 个答案:

答案 0 :(得分:2)

scala> sampleObj.getClass.getDeclaredFields.map(f => f.getName)
res3: Array[String] = Array(firstname, lastname)

我们可以使用Java getDeclaredFields获取sampleClass中的所有字段,您知道scala基于Java