在 Scala 中调用反射案例类构造函数 [英] Invoking reflected case class constructor in Scala

查看:91
本文介绍了在 Scala 中调用反射案例类构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以这样通过静态反射获得一个案例类的默认构造函数:

I can get the default constructor of a case class via static reflection thusly:

val symbol = currentMirror.classSymbol(myObj.getClass).typeSignature.typeSymbol.asClass
val ctor = symbol.primaryConstructor

从这里我可以做一些漂亮的事情,比如内省其字段的细节等.但是我现在如何调用构造函数方法?我可以深入研究 myObj 的类,但如果它有多个构造函数,是否有一种简单的方法可以将正确的构造函数与我从 primaryConstructor 获得的构造函数相匹配?

From here I can do nifty things like introspect details of its fields, etc. But how can I now invoke the constructor method? I could dig into myObj's class, but if it has multiple constructors, is there a straightforward way to match the right constructor to the one I got from primaryConstructor?

推荐答案

可以在类镜像上使用reflectConstructor方法:

You can use the reflectConstructor method on the class mirror:

val classMirror = currentMirror.reflectClass(typeOf[Foo].typeSymbol.asClass)
classMirror.reflectConstructor(ctor.asMethod).apply(2, "bar").asInstanceOf[Foo]

这篇关于在 Scala 中调用反射案例类构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆