yourspraveen
yourspraveen

Reputation: 13

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

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

Upvotes: 1

Views: 387

Answers (1)

Jasper-M
Jasper-M

Reputation: 15086

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).

Upvotes: 1

Related Questions