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!)
erasureis of typejava.lang.Class, so you can use constructors (anyway you don’t need manifest in this simple case – you can just useclassOf[C]). Instead of callingnewinstancedirectly, you can at first find correspondent constructor withgetConstructormethod (with correspondent argument types), and then just callnewInstanceon it: