Scala与Java的ClassName.class等效吗?


84

我如何Class在Scala中获取实例?在Java中,我可以这样做:

Class<String> stringClass = String.class;

Scala中的等效值是多少?

Answers:


105

其中有一个方法classOfscala.Predef用于检索类类型的运行时表示形式。

val stringClass = classOf[String]

您可以使用该getClass方法以与Java相同的方式在运行时获取实例的类对象。

scala> val s = "hello world"
s: String = hello world

scala> s.getClass
res0: Class[_ <: String] = class java.lang.String
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.