Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Invoking reflected case class constructor in Scala

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?

like image 404
Greg Avatar asked May 14 '26 21:05

Greg


1 Answers

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]
like image 178
Ben Reich Avatar answered May 17 '26 15:05

Ben Reich