我怎样才能轻松得到一个斯卡拉案例类的名字?

鉴于:

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

我怎样才能从one.name"SecondCC"two.name获得"FirstCC"

 def name = this.getClass.getName 

或者如果你只想要没有包的名字:

 def name = this.getClass.getSimpleName 

有关更多信息,请参阅java.lang.Class的文档。

您可以使用案例类的属性productPrefix

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

NB如果你传递给Scala 2.8扩展一个case类已经被弃用了,你不得不忘记左边和右边的parent ()

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

这是一个Scala函数,可以从任何types生成一个人类可读的string,recursiontypes参数:

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] }