Reputation: 203
Assuming the following code:
package my.package
case class ExampleCaseClass(s: String, i: Int, ...)
object ExampleCaseClass {
val instance = ExampleCaseClass("number", 5, ...)
}
how can I extract class info and data using Scala reflection if the only reference is a string, say my.package.ExampleCaseClass.instance
or something along these lines?
In other words, I want to have a function getInfo: String => String
which does, say, the following:
getInfo("my.package.ExampleCaseClass.instance") =
"ExampleCaseClass ( s: number, i: 5, ... )"
Upvotes: 0
Views: 212
Reputation: 14803
This uses Java Class.forName
:
def getInfo(className: String = "finnova.bpf.report.entity.DocumentBarcode") = {
val fields =
Class.forName(className).getDeclaredFields
.map(f => s"${f.getName}: ${f.getType.getSimpleName}")
.mkString("(", ", ", ")")
s"$className$fields"
}
This uses scala.reflect
import scala.reflect._
def getInfo(className: String = "finnova.bpf.report.entity.DocumentBarcode") = {
val classSymbol = runtime.currentMirror.classSymbol(Class.forName(className))
val primCtor = classSymbol.info.decls.find(m => m.isMethod && m.asMethod.isPrimaryConstructor).get
val fields = primCtor.typeSignature.paramLists.head
.map(f => s"${f.name}: ${f.info.resultType}").mkString("(", ", ",")")
s"$className$fields"
}
This is a bit more involved, but you get much more information. Here is a nice blog that gets you started: https://medium.com/@giposse/scala-reflection-d835832ed13a
Upvotes: 1