首页 > 解决方案 > 如何获得混合特征的具体类

问题描述

假设我具有以下特征和类别:

trait A {
    def foo(): Unit
}

trait B extends A {
    abstract override def foo(): Unit = {
        // Can I determine the name of the concrete class here?
        super.foo()
    }
}

class C extends A {
    def foo() = {
        println("C::foo()")
    }
}

val c = new C with B
c.foo()

有没有办法从特征 B 中确定实例化它的具体类的名称?即C

标签: scalainheritanceoverriding

解决方案


尝试.getClass.getSuperclass.getSimpleName

trait A {
  def foo(): Unit
}

trait B extends A {
  abstract override def foo(): Unit = {
    println("B is instantiated in " + getClass.getSuperclass.getSimpleName)
    super.foo()
  }
}

class C extends A {
  def foo() = {
    println("C::foo()")
  }
}

val c = new C with B
c.foo()
//B is instantiated in C
//C::foo()

推荐阅读