Como posso facilmente obter o nome de uma classe do caso Scala?
Pergunta
Dado:
case class FirstCC {
def name: String = ... // something that will give "FirstCC"
}
case class SecondCC extends FirstCC
val one = FirstCC()
val two = SecondCC()
Como posso obter "FirstCC"
a partir de one.name
e "SecondCC"
a partir de two.name
?
Solução
def name = this.getClass.getName
Ou se você quiser apenas o nome sem o pacote:
def name = this.getClass.getSimpleName
Veja a documentação de java.lang.class Para maiores informações.
Outras dicas
Você pode usar a propriedade productPrefix
da classe de caso:
case class FirstCC {
def name = productPrefix
}
case class SecondCC extends FirstCC
val one = FirstCC()
val two = SecondCC()
one.name
two.name
NB Se você passar para Scala 2.8, estendendo uma classe de caso foi preterido e você não deve esquecer o pai esquerdo e direito ()
class Example {
private def className[A](a: A)(implicit m: Manifest[A]) = m.toString
override def toString = className(this)
}
def name = this.getClass.getName
Aqui está uma função Scala que gera uma string legível por humanos de qualquer tipo, com parâmetros de tipo no tipo:
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]
}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow