Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In scala, use reflection on a case class classtag to find the companion object's apply method

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.

like image 846
jonderry Avatar asked Dec 04 '25 14:12

jonderry


1 Answers

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
}
like image 123
Klaus Avatar answered Dec 07 '25 08:12

Klaus



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!