gpt4 book ai didi

scala - 从构造函数参数值映射创建类实例

转载 作者:行者123 更新时间:2023-12-01 07:39:30 26 4
gpt4 key购买 nike

假设我有以下类(class):

case class Mock(id: Int, pty1: String, pty2: String)

我如何从下面的 map 动态实例化它?

val params = Map("id" → 234, "pty1" → "asdf", "pty2" → "asdf")

最佳答案

大声笑)发现我的库中已经实现了一个解决方案。需要 Scala 2.10。

  def instantiate[T <: AnyRef : Manifest](params: Map[String, Any]): T = {
instantiate(Mirror.classToType(manifest[T].erasure), params).asInstanceOf[T]
}
def instantiate(tpe: Mirror.Type, params: Map[String, Any]) = {
val p = constructorParams(tpe, params)
require(
params.size == p.size &&
p.forall(p => params.contains(p.nameString)),
"Params map `" + params + "` doesn't match `" + p + "`"
)
Option(Mirror.typeToJavaClass(tpe).getConstructor(p.map(p => Mirror.typeToJavaClass(p.tpe)): _*))
.getOrElse(throw new RuntimeException("No appropriate constructor of `" + tpe + "` found"))
.newInstance(p.map(p => params(p.nameString).asInstanceOf[Object]): _*)
}
private def constructorParams(tpe: Mirror.Type, params: Map[String, Any]) = {
tpe.members.find(_.isConstructor).get.paramss(0)
}

关于scala - 从构造函数参数值映射创建类实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8611616/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com