mercredi 6 avril 2016

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





Aucun commentaire:

Enregistrer un commentaire