如何轻松获得 Scala case 类的名称?

给出:

case class FirstCC {
def name: String = ... // something that will give "FirstCC"
}
case class SecondCC extends FirstCC
val one = FirstCC()
val two = SecondCC()

如何从 one.name中获得 "FirstCC",从 two.name中获得 "SecondCC"

65276 次浏览
def name = this.getClass.getName
class Example {
private def className[A](a: A)(implicit m: Manifest[A]) = m.toString
override def toString = className(this)
}
def name = this.getClass.getName

或者,如果您只想要没有包的名称:

def name = this.getClass.getSimpleName

有关更多信息,请参见 Java.lang 同学们的文档。

您可以使用 case 类的属性 productPrefix:

case class FirstCC {
def name = productPrefix
}
case class SecondCC extends FirstCC
val one = FirstCC()
val two = SecondCC()


one.name
two.name

注意。 如果您传递给 scala 2.8扩展 case 类已经被弃用,并且您不能忘记左右两个父类 ()

下面是一个 Scala 函数,它从任何类型生成一个人类可读的字符串,并在类型参数上递归:

Https://gist.github.com/erikerlandson/78d8c33419055b98d701

import scala.reflect.runtime.universe._


object TypeString {


// return a human-readable type string for type argument 'T'
// typeString[Int] returns "Int"
def typeString[T :TypeTag]: String = {
def work(t: Type): String = {
t match { case TypeRef(pre, sym, args) =>
val ss = sym.toString.stripPrefix("trait ").stripPrefix("class ").stripPrefix("type ")
val as = args.map(work)
if (ss.startsWith("Function")) {
val arity = args.length - 1
"(" + (as.take(arity).mkString(",")) + ")" + "=>" + as.drop(arity).head
} else {
if (args.length <= 0) ss else (ss + "[" + as.mkString(",") + "]")
}
}
}
work(typeOf[T])
}


// get the type string of an argument:
// typeString(2) returns "Int"
def typeString[T :TypeTag](x: T): String = typeString[T]
}
def name = getClass.getSimpleName.split('$').head

这将删除出现在一些类的末尾的 $1