如何获取 Scala 对象类型的 classOf
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9635563/
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
How the get the classOf for a scala object type
提问by Martin
I wonder how to get a class object for an object type in Scala. Ok, that is a mouth full because of the double meaning for object. So here an example which will fail:
我想知道如何在 Scala 中获取对象类型的类对象。好吧,这是因为对象的双重含义而满嘴。所以这里有一个失败的例子:
object Main
{
private [this] val TAG = classOf [Main].getName;
} // Main
If Mainwas class it works perfectly. Any ideas?
如果Main是课堂,它就完美无缺。有任何想法吗?
回答by Alexey Romanov
scala> Main.getClass
res1: java.lang.Class[_] = class Main$
回答by Jesper
The reason why classOf[Main]doesn't work is because Mainis not a type.
classOf[Main]不起作用的原因是因为Main不是type。
Classes and traits define types, objects do not.
类和特征定义了类型,而对象没有。
回答by Joachim Isaksson
Since Main is an object, for your example to work, simply replace your assignment line with;
由于 Main 是一个对象,为了让您的示例工作,只需将您的分配行替换为;
private [this] val TAG = this.getClass.getName;

