In Scala, I can declare an object like so:

class Thing

object Thingy extends Thing

How would I get "Thingy" (the name of the object) in Scala?

I've heard that Lift (the web framework for Scala) is capable of this.

有帮助吗?

解决方案

Just get the class object and then its name.

scala> Thingy.getClass.getName
res1: java.lang.String = Thingy$

All that's left is to remove the $.

EDIT:

To remove names of enclosing objects and the tailing $ it is sufficient to do

res1.split("\\$").last

其他提示

If you declare it as a case object rather than just an object then it'll automatically extend the Product trait and you can call the productPrefix method to get the object's name:

scala> case object Thingy
defined module Thingy

scala> Thingy.productPrefix
res4: java.lang.String = Thingy

I don't know which way is the proper way, but this could be achieved by Scala reflection:

implicitly[TypeTag[Thingy.type]].tpe.termSymbol.name.toString
def nameOf[T](implicit ev: ClassTag[T]):String = ev.runtimeClass.getName.replace("$", "")
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top