Calling a constructor through reflection in scala 2.10

坚强是说给别人听的谎言 提交于 2019-12-24 01:27:08

问题


What's the best practice for calling a constructor of a class in scala 2.10 (M4+) ?


回答1:


Answering my own question: Calling the constructor is different than invoking a method. Here's the right way to do it in scala 2.10

import reflect.runtime.universe._
import reflect.runtime.currentMirror
val typ = typeOf[Range]
val constructor = typ.members.find(_.kind == "constructor").get.asMethodSymbol
currentMirror reflectClass typ.typeSymbol.asClassSymbol reflectConstructor constructor apply (1,10,1)

As expected, the result is:

res7: Any = Range(1, 2, 3, 4, 5, 6, 7, 8, 9)


来源:https://stackoverflow.com/questions/11755735/calling-a-constructor-through-reflection-in-scala-2-10

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!