如何确定 Scala 中对象的 class?

How can I determine the class of an object in Scala?

我需要检查 y 严格来说是 bar 的一个实例,而不是 foo .我如何在 Scala 中执行此操作?

trait foo {}

trait bar extends foo {}

val x = new foo {}
val y = new bar {}

x.isInstanceOf[foo] // true
x.isInstanceOf[bar] // false

y.isInstanceOf[bar] // true
y.isInstanceOf[foo] // true (but I want it to return false)
如果您只创建新实例,

getClass 会起作用。但是您正在创建新的匿名 类 和它们的实例。

对于那些与 foo 和与 bar 的关系完全相同:它们是超级类。

你的问题标题是class,但实际问题使用的是特征。您可以使用 classes 通过运行时反射来执行类似的操作。让我们创建一个方便的方法来获取 object:

reflect.runtime.universe.Type
import scala.reflect.runtime.universe._

def tpeOf[A](a: A)(implicit tt: TypeTag[A]): Type = tt.tpe

还有一些样本 classes:

class Foo
class Bar extends Foo
val x = new Foo
val y = new Bar

我们可以用我们的tpeOf方法得到xyType,并与[=的Type进行比较20=] 使用 typeOf 获得。这将产生您想要的结果。

scala> tpeOf(x) =:= typeOf[Foo]
res0: Boolean = true

scala> tpeOf(x) =:= typeOf[Bar]
res1: Boolean = false

scala> tpeOf(y) =:= typeOf[Foo]
res2: Boolean = false

scala> tpeOf(y) =:= typeOf[Bar]
res3: Boolean = true

但这不适用于特征,因为在您的示例中 y 而不是 bar 的实例,它是匿名 class 扩展 bar。所以使用这种方法总是会产生 false.

trait foo {}
trait bar extends foo {}
val x = new foo {}
val y = new bar {}

scala> tpeOf(x) =:= typeOf[bar]
res4: Boolean = false   // As expected, `x` is not exactly `bar`