I can get the default constructor of a case class via static reflection thusly:
val symbol = currentMirror.classSymbol(myObj.getClass).typeSignature.typeSymbol.asClass
val ctor = symbol.primaryConstructor
From here I can do nifty things like introspect details of its fields, etc. But how can I now invoke the constructor method? I could dig into myObj's class, but if it has multiple constructors, is there a straightforward way to match the right constructor to the one I got from primaryConstructor?
You can use the reflectConstructor method on the class mirror:
val classMirror = currentMirror.reflectClass(typeOf[Foo].typeSymbol.asClass)
classMirror.reflectConstructor(ctor.asMethod).apply(2, "bar").asInstanceOf[Foo]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With