Is there any way to 'dynamically'/reflectively/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 that compiles. (This is also, rest assured, being used in a context that makes much more sense than this simplified example!)
erasure
is of type java.lang.Class
, so you can use constructors (anyway you don't need manifest in this simple case - you can just use classOf[C]
). Instead of calling newinstance
directly, you can at first find correspondent constructor with getConstructor
method (with correspondent argument types), and then just call newInstance
on it:
classOf[C].getConstructor(classOf[String]).newInstance("string")