在 Scala 中,如何获取“对象”(不是类的实例)的 *name*?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12995250/
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
In Scala, how do I get the *name* of an `object` (not an instance of a class)?
提问by Scoobie
In Scala, I can declare an object like so:
在 Scala 中,我可以像这样声明一个对象:
class Thing
object Thingy extends Thing
How would I get "Thingy"(the name of the object) in Scala?
我将如何"Thingy"在 Scala 中获得(对象的名称)?
I've heard that Lift (the web framework for Scala) is capable of this.
我听说 Lift(Scala 的 Web 框架)能够做到这一点。
回答by DaoWen
If you declare it as a case objectrather than just an objectthen it'll automatically extend the Producttraitand you can call the productPrefixmethod to get the object's name:
如果你将它声明为 acase object而不仅仅是 anobject那么它会自动扩展Product特性,你可以调用该productPrefix方法来获取对象的名称:
scala> case object Thingy
defined module Thingy
scala> Thingy.productPrefix
res4: java.lang.String = Thingy
回答by Kim Stebel
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
回答by Jacek L.
I don't know which way is the proper way, but this could be achieved by Scala reflection:
我不知道哪种方式是正确的方式,但这可以通过 Scala 反射来实现:
implicitly[TypeTag[Thingy.type]].tpe.termSymbol.name.toString

