开发者

newInstance with arguments

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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜