在 Scala 中,对 case 类 classtag 使用反射来查找伴随对象的 apply 方法 [英] In scala, use reflection on a case class classtag to find the companion object's apply method
本文介绍了在 Scala 中,对 case 类 classtag 使用反射来查找伴随对象的 apply 方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这与以下问题有关,但由于它涉及一个明显且突出的问题,因此我将其作为跟进:支持从 Scala 中的 List[(String, Any)] 进行通用反序列化
This is related to the following question, but since it concerns a distinct and salient issue, I'm asking it as a follow up: Support generic deserialization from a List[(String, Any)] in Scala
如何使用反射来查找 ClassTag
的伴随对象的方法?具体来说,我试图反射性地调用案例类的伴随对象的 apply
方法来构造案例类的实例.
How can I use reflection to find the methods of the companion object for a ClassTag
? Specifically, I'm trying to call the apply
method of a case class' companion object reflectively to construct an instance of a case class.
推荐答案
Could 这个答案 对你有帮助吗?
Could this answer help you?
这是一个 scalaVersion :="2.11.1"
import scala.reflect.runtime.{universe => u}
def companionMembers(clazzTag: scala.reflect.ClassTag[_]): u.MemberScope = {
val runtimeClass = clazzTag.runtimeClass
val rootMirror = u.runtimeMirror(runtimeClass.getClassLoader)
val classSymbol = rootMirror.classSymbol(runtimeClass)
// get the companion here
classSymbol.companion.typeSignature.members
}
case class MyClass(value: Int)
val applyMethods =
companionMembers(scala.reflect.classTag[MyClass])
.filter { m => m.isMethod && m.name.toString == "apply"}
println(applyMethods)
印刷品
Scope{
case def apply(value: scala.Int): MyClass
}
这篇关于在 Scala 中,对 case 类 classtag 使用反射来查找伴随对象的 apply 方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文