68

鉴于:

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

4

6 回答 6

106
def name = this.getClass.getName

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

def name = this.getClass.getSimpleName

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

于 2010-04-16T22:38:49.553 回答
25

您可以使用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 扩展案例类已被弃用,你必须不要忘记左右父级()

于 2010-04-16T23:02:45.960 回答
16
class Example {
  private def className[A](a: A)(implicit m: Manifest[A]) = m.toString
  override def toString = className(this)
}
于 2010-04-16T22:37:59.710 回答
11
def name = this.getClass.getName
于 2010-04-16T22:29:45.967 回答
8

这是一个 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]
}
于 2015-01-23T14:37:15.767 回答
4
def name = getClass.getSimpleName.split('$').head

这将删除$1某些课程最后出现的内容。

于 2020-07-20T09:01:04.667 回答