How to invoke default constructor using scala reflection if we have default value defined in our constructor

你。 提交于 2021-01-28 21:15:00

问题


class Person(name: String = "noname", age:Int = -1){}

object ReflectionTester{
 def main(args: Array[String]) {
  val m = ru.runtimeMirror(getClass.getClassLoader)
  val classTest = m.staticClass("Person")
  val theType = classTest.toType

  //class mirror
  val cm = m.reflectClass(classTest)
  val ctor = theType.decl(ru.termNames.CONSTRUCTOR).asMethod
 }
}

Invoking class mirror gives me the default constructor of passing name and age but there are inferred constructor too right where i can create a person with default values and allow me to set them as needed.

How do you invoke that in method mirror. I'm expecting 4 constructors in this case 1 with both values and 2 for individual fields and 1 with no fields.

I choose this as an example VO so please don't comment on the design. The question is on how to infer the constructors with default values


回答1:


There is only one constructor. The default values are kept in the Person companion object. A call new Person(age = 10) is turned into something like new Person(Person.<init>$default$1(), 10).



来源:https://stackoverflow.com/questions/36457467/how-to-invoke-default-constructor-using-scala-reflection-if-we-have-default-valu

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!