获取传递给Scala中的类的所有参数

时间:2017-01-06 01:21:00

标签: scala

通常可以获取给予类的所有参数/构造函数参数吗?

类似的东西:

trait GetMyArgs {
    def myArgs = ???
}

class Foo(i: Int, d: Double) extends GetMyArgs

=>

scala> val f = new Foo(5, 6.6)
scala> f.myArgs
(5, 6.6) // or similar

2 个答案:

答案 0 :(得分:0)

  def myArgs = {
    this.getClass.getDeclaredFields
      .toList
      .map(i => {
        i.setAccessible(true)
        i.getName -> i.get(this)
      }).toMap
  }

您只需使用 java reflection即可。但需要调用,如果变量不使用且构造函数参数不是valmyArgs将输出 Map

答案 1 :(得分:0)

以下与上述示例相同,但以排序形式:)

def myArgs: List[(String, AnyRef)] = {
    this.getClass.getDeclaredFields.toList
      .map(i => {
        i.setAccessible(true)
        i.getName -> i.get(this)
      })
  }
相关问题