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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2656364/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-22 02:04:50  来源:igfitidea点击:

How can I easily get a Scala case class's name?

scalaclassclassname

提问by pr1001

Given:

鉴于:

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

How can I get "FirstCC"from one.nameand "SecondCC"from two.name?

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

回答by Esko Luontola

def name = this.getClass.getName

Or if you want only the name without the package:

或者,如果您只想要名称而不需要包:

def name = this.getClass.getSimpleName

See the documentation of java.lang.Classfor more information.

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

回答by Patrick

You can use the property productPrefixof the case class:

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

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

one.name
two.name

N.B. If you pass to scala 2.8 extending a case class have been deprecated, and you have to not forget the left and right parent ()

NB如果你传递给scala 2.8扩展案例类已被弃用,你必须不要忘记左右父级 ()

回答by Daniel C. Sobral

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

回答by Rex Kerr

def name = this.getClass.getName

回答by eje

Here is a Scala function that generates a human-readable string from any type, recursing on type parameters:

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

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

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