If I have a class like this:
case class Key(
id: Long,
var text: String,
var `type`: String
)
Is there any way to get from that class the list of arguments like this:
['id', 'text', 'type']
If so, how would I do that? Thanks!
If I have a class like this:
case class Key(
id: Long,
var text: String,
var `type`: String
)
Is there any way to get from that class the list of arguments like this:
['id', 'text', 'type']
If so, how would I do that? Thanks!
I don't know the solution for myself, but I found this on github:
https://gist.github.com/heathermiller/354befb88b097330d42d
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]
}
I hope this might help. I know that it's not exactly what you was looking for, but you can adjust this solution for yourself.