如何轻松获取Scala案例类的名称?

时间:2010-04-16 22:10:09

标签: scala class classname

假设:

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

如何从"FirstCC" one.name"SecondCC"获取two.name

6 个答案:

答案 0 :(得分:81)

def name = this.getClass.getName

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

def name = this.getClass.getSimpleName

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

答案 1 :(得分:20)

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

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

one.name
two.name

N.B。 如果您传递给scala 2.8,则不推荐使用扩展案例类,并且您不必忘记左右父()

答案 2 :(得分:14)

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

答案 3 :(得分:11)

def name = this.getClass.getName

答案 4 :(得分:5)

这是一个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]
}

答案 5 :(得分:2)

def name = getClass.getSimpleName.split('$').head

这将删除在某些课程末尾出现的$1