Reputation: 11512
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?
Upvotes: 3
Views: 483
Reputation: 16324
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]
Upvotes: 3