Calling a constructor through reflection in scala

2019-07-16 11:14发布

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

1条回答
Anthone
2楼-- · 2019-07-16 12:20

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)
查看更多
登录 后发表回答