开发者

newInstance with arguments

开发者 https://www.devze.com 2023-02-18 17:25 出处:网络
Is there any way to \'dynamically\'/reflectively/etc create a new instance of a class with arguments i开发者_C百科n Scala?

Is there any way to 'dynamically'/reflectively/etc create a new instance of a class with arguments i开发者_C百科n 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")
0

精彩评论

暂无评论...
验证码 换一张
取 消