问题描述
有什么方法可以动态"/反射/等在 Scala 中创建带有参数的类的新实例?
Is there any way to 'dynamically'/reflectively/etc create a new instance of a class with arguments in Scala?
例如,类似于:
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
是 java.lang.Class
类型,所以你可以使用构造函数(无论如何你不在这种简单的情况下不需要清单 - 你可以只使用 classOf[C]
).不是直接调用 newinstance
,你可以先用 getConstructor
方法找到对应的构造函数(对应的参数类型),然后调用 newInstance
它:
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")
这篇关于带参数的新实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!