【发布时间】:2019-03-10 23:36:56
【问题描述】:
我需要能够通过反射来实例化各种案例类,既要弄清楚构造函数的参数类型,又要使用所有默认参数调用构造函数。
我已经做到了:
import reflect.runtime.{universe => ru}
val m = ru.runtimeMirror(getClass.getClassLoader)
case class Bar(i: Int = 33)
val tpe = ru.typeOf[Bar]
val classBar = tpe.typeSymbol.asClass
val cm = m.reflectClass(classBar)
val ctor = tpe.declaration(ru.nme.CONSTRUCTOR).asMethod
val ctorm = cm.reflectConstructor(ctor)
// figuring out arg types
val arg1 = ctor.paramss.head.head
arg1.typeSignature =:= ru.typeOf[Int] // true
// etc.
// instantiating with given args
val p = ctorm(33)
现在缺少的部分:
val p2 = ctorm() // IllegalArgumentException: wrong number of arguments
那么如何使用Bar 的默认参数创建p2,即没有反射的Bar()。
【问题讨论】:
-
相关:stackoverflow.com/questions/14034142/… - Travis 的回答很简洁,但似乎
nme.defaultGetterName不再存在(Scala 2.10.1)
标签: scala reflection