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.
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With