In scala, use reflection on a case class classtag

2019-07-04 21:02发布

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

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.

1条回答
神经病院院长
2楼-- · 2019-07-04 21:16

Could this answer help you?

Here is an example for 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)

prints

Scope{
  case def apply(value: scala.Int): MyClass
}
查看更多
登录 后发表回答