In Scala, how do I get the *name* of an `object` (not an instance of a class)?

自闭症网瘾萝莉.ら 提交于 2019-12-20 09:36:32

问题


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.


回答1:


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



回答2:


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



回答3:


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


来源:https://stackoverflow.com/questions/12995250/in-scala-how-do-i-get-the-name-of-an-object-not-an-instance-of-a-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!