3

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.

Community
  • 1
  • 1
jonderry
  • 23,013
  • 32
  • 104
  • 171

1 Answers1

4

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
}
Community
  • 1
  • 1
Klaus
  • 885
  • 7
  • 11
  • Yes, something like this works ok. I ended up using `private val apply = ctag.runtimeClass.getDeclaredMethods.find(m => "apply".equals(m.getName)).get`. – jonderry May 30 '14 at 23:21