Forked from heathermiller/reflect-extract-ctor-args.scala
Created
April 7, 2020 14:47
-
-
Save adarshaj/18c631e9853fc77084b3d520c7ea4b76 to your computer and use it in GitHub Desktop.
Getting constructor arguments out of a case class, printing the names of the args and their runtime values
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import scala.reflect.runtime.universe._ | |
class AbstractParams[T: TypeTag] { | |
def tag: TypeTag[T] = typeTag[T] | |
override def toString: String = { | |
// Find all case class fields in concrete class instance and print them as "[field name] [field value]" | |
val tag = this.tag | |
val tpe = tag.tpe | |
val allAccessors = tpe.declarations.collect { case meth: MethodSymbol if meth.isCaseAccessor => meth } | |
val m = runtimeMirror(getClass.getClassLoader) | |
val im = m.reflect(this) | |
val ctorArg2Strings = allAccessors map { sym => | |
val fldMirror = im.reflectField(sym) | |
val value = fldMirror.get | |
"[" + sym.name + ": " + value + "]" | |
} | |
ctorArg2Strings.mkString(" ") | |
} | |
} | |
case class MyParams(id: String, stuff: Int) extends AbstractParams[MyParams] | |
object Ex extends App { | |
val p = new MyParams("joe", 2) | |
println(s"$p") | |
// prints: | |
// [id: joe] [stuff: 2] | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment