NewInstance with arguments

Is there a way to dynamically / reflexively / etc create a new instance of a class with arguments in Scala?

For example, something like:

class C(x: String)
manifest[C].erasure.newInstance("string")

But it compiles. (This also, you can be sure, is used in a context that makes much more sense than this simplified example!)

+3
source share
1 answer

erasurehas a type java.lang.Class, so you can use constructors (in any case, you do not need a manifest in this simple case - you can just use it classOf[C]). Instead of calling directly, newinstanceyou can first find the correspondence constructor using the method getConstructor(with the corresponding argument types), and then simply call newinstanceon it:

classOf[C].getConstructor(classOf[String]).newInstance("string")
+11
source

All Articles