如何在 scala 中显示 case class 的值

how to display value of case class in scala

case class Keyword(id: Int = 0, words: String)

val my= Keyword(123, "hello")

val fields: Array[Field] = my.getClass.getDeclaredFields

for (i <- fields.indices) {

  println(fields(i).getName +":"+ my.productElement(i))

}

id:123

title:关键字的标题

没关系。

def outputCaseClass[A](obj:A){

  val fields: Array[Field] = obj.getClass.getDeclaredFields

  for (i <- fields.indices) {

    println(fields(i).getName +":"+ obj.productElement(i))

  }
}

outputCaseClass(my)

错了

productElement 是 Product 基本特征的方法。

尝试使用这样的方法签名:

def outputCaseClass[A <: Product](obj:A){ .. }

但是它仍然不适用于内部案例 类(fields 还报告 $outer-Field,而 productElement 不会 return 等等IndexOutOfBoundsException).

崩溃
import scala.reflect.runtime.{universe => ru}

def printCaseClassParams[C: scala.reflect.ClassTag](instance: C):Unit = {
  val runtimeMirror = ru.runtimeMirror(instance.getClass.getClassLoader)
  val instanceMirror = runtimeMirror.reflect(instance)
  val tpe = instanceMirror.symbol.toType

  tpe.members
    .filter(member => member.asTerm.isCaseAccessor && member.asTerm.isMethod)
    .map(member => {
      val term = member.asTerm
      val termName = term.name.toString
      val termValue = instanceMirror.reflectField(term).get
      termName + ":" + termValue
    })
    .toList
    .reverse
    .foreach(s => println(s))
}

// Now you can use it with any case classes,

case class Keyword(id: Int = 0, words: String)

val my = Keyword(123, "hello")

printCaseClassParams(my)
// id:123
// words:hello