Java 的 ClassName.class 的 Scala 等价物是什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1166732/
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
What is the Scala equivalent of Java's ClassName.class?
提问by Daniel C. Sobral
How do I get an instance of Classin Scala? In Java, I can do this:
我如何Class在 Scala 中获得一个实例?在 Java 中,我可以这样做:
Class<String> stringClass = String.class;
What would be the equivalent in Scala?
Scala 中的等价物是什么?
回答by oxbow_lakes
There is a method classOfin scala.Predefthat retrieves the runtime representation of a class type.
有一种方法classOf在scala.Predef检索的类类型的运行时表示。
val stringClass = classOf[String]
You can use the getClassmethod to get the class object of an instance at runtime in the same manner as Java
您可以使用该getClass方法以与Java相同的方式在运行时获取实例的类对象
scala> val s = "hello world"
s: String = hello world
scala> s.getClass
res0: Class[_ <: String] = class java.lang.String

