scala 有没有办法在没有示例实例的情况下生成通用实例?
我正在尝试创建一个通用工厂,如下所示:
trait Factory[T] { def createInstance():T = new T() }
val dateFactory = new Factory[Date](){}
val myDate = dateFactory.createInstance()
“new T()”无法编译,因为 T 在运行时之前是未定义的。我知道我可以通过将类的实例传递给某种方法(即 createInstance(classOf[Date]) )来使其工作,
我问是否有一些内省魔法可以取代“new T()”,所以我可以创建我的超级简单工厂吗?
I was playing with creating a generic factory as follows:
trait Factory[T] { def createInstance():T = new T() }
val dateFactory = new Factory[Date](){}
val myDate = dateFactory.createInstance()
The 'new T()' doesn't compile, as T is undefined until runtime. I know that I can get it to work by passing in an instance of the class to some method (ie. createInstance(classOf[Date]) )
I am asking if there is some introspection magic that could replace 'new T()' so that I can create my super simple factory?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这将起作用:
如果为其实例化的类具有默认(零参数)构造函数。
This will work:
if the class for which it is instantiated has a default (zero-arg) constructor.