Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

newInstance with arguments

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!)

like image 329
Aaron Yodaiken Avatar asked Dec 09 '22 10:12

Aaron Yodaiken


1 Answers

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")
like image 123
tenshi Avatar answered Dec 25 '22 02:12

tenshi